File size: 4,106 Bytes
a110318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build a 300,000-sequence OpenWebText training corpus, disjoint from the
existing test split.

Follows the conventions of eda_phase0/stage1_02b exactly, so the new corpus is
the same KIND of data as the 10,000-sequence train split it replaces:
  * stream Skylion007/openwebtext with shuffle(seed=SEED, buffer=30,000)
  * tokenise each document with truncation to 127 content tokens
  * keep only documents that yield exactly 127 (i.e. long enough)
  * prepend the BOS token to make a 128-token sequence

DISJOINTNESS is enforced structurally at the end: any sequence byte-identical
to a test sequence is dropped and the count is reported. The test split is NOT
regenerated -- it stays exactly as shipped, so every number produced from this
corpus is directly comparable to the numbers already in the repo.
"""
from __future__ import annotations
import json, sys, time
from pathlib import Path
import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(ROOT / "eda_phase0"))
import config as C

TARGET = 300_000
OUT = HERE / "corpus_300k.npz"


def main() -> None:
    from transformers import AutoTokenizer
    from datasets import load_dataset

    tok = AutoTokenizer.from_pretrained("gpt2")
    ds = load_dataset(C.OWT_DATASET, split="train", streaming=True)
    ds = ds.shuffle(seed=C.SEED, buffer_size=C.OWT_SHUFFLE_BUFFER)

    seqs: list[np.ndarray] = []
    pulled = discarded = 0
    t0 = time.time()
    for ex in ds:
        pulled += 1
        ids = tok(ex["text"], truncation=True,
                  max_length=C.OWT_CONTENT_TOKENS)["input_ids"]
        if len(ids) == C.OWT_CONTENT_TOKENS:
            seqs.append(np.asarray(ids, dtype=np.int32))
        else:
            discarded += 1
        if pulled % 25_000 == 0:
            print(f"  pulled {pulled:,}  kept {len(seqs):,}  "
                  f"{(time.time()-t0)/60:.1f} min", flush=True)
        if len(seqs) >= TARGET:
            break

    pool = np.stack(seqs)
    full = np.zeros((len(pool), C.OWT_SEQ_LEN), dtype=np.int32)
    full[:, 0] = C.BOS_TOKEN_ID
    full[:, 1:] = pool
    print(f"\nbuilt {len(full):,} sequences from {pulled:,} documents "
          f"({discarded:,} too short), {(time.time()-t0)/60:.1f} min")

    # structural disjointness from the shipped test split, and self-dedup
    te = np.load(C.CACHE / "owt_test_tokens.npz")["tokens"]
    sig_te = set(map(bytes, np.ascontiguousarray(te)))
    sig_seen: set[bytes] = set()
    keep = np.ones(len(full), bool)
    dup_test = dup_self = 0
    for i, row in enumerate(np.ascontiguousarray(full)):
        b = bytes(row)
        if b in sig_te:
            keep[i] = False; dup_test += 1
        elif b in sig_seen:
            keep[i] = False; dup_self += 1
        else:
            sig_seen.add(b)
    full = full[keep]
    print(f"dropped {dup_test:,} duplicates of TEST and {dup_self:,} internal "
          f"duplicates -> {len(full):,} sequences")

    tr = np.load(C.CACHE / "owt_train_tokens.npz")["tokens"]
    overlap_tr = len(set(map(bytes, np.ascontiguousarray(tr))) &
                     set(map(bytes, np.ascontiguousarray(full))))
    n_read = len(full) * (C.OWT_SEQ_LEN - C.FIRST_READ_POSITION)
    print(f"contains {overlap_tr:,} of the original 10,000 train sequences "
          f"(expected: it is a superset of the same stream)")
    print(f"read positions: {n_read:,}  "
          f"({n_read / 1_270_000:.1f}x the shipped train corpus)")

    np.savez_compressed(OUT, tokens=full)
    (HERE / "corpus_info.json").write_text(json.dumps({
        "dataset": C.OWT_DATASET, "seed": C.SEED,
        "shuffle_buffer": C.OWT_SHUFFLE_BUFFER,
        "documents_pulled": pulled, "documents_too_short": discarded,
        "sequences": int(len(full)), "seq_len": C.OWT_SEQ_LEN,
        "read_positions": int(n_read),
        "dropped_dup_of_test": dup_test, "dropped_dup_internal": dup_self,
        "overlap_with_test": 0, "overlap_with_old_train": overlap_tr,
        "test_split": "owt_test_tokens.npz, unchanged",
    }, indent=2))
    print(f"wrote {OUT}")


if __name__ == "__main__":
    main()