File size: 8,907 Bytes
fbe8d49
 
 
 
 
 
 
 
 
 
 
9cd89ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbe8d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
9cd89ed
 
fbe8d49
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
9cd89ed
fbe8d49
 
 
 
 
9cd89ed
 
 
 
fbe8d49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
9cd89ed
fbe8d49
 
 
 
 
 
 
 
 
 
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
"""Streaming adapters. Each yields dicts: {"text"} or {"turns": [(speaker, text)]}, optional "title"."""
import ast
import random
import re
import zlib

from datasets import load_dataset
from huggingface_hub import HfFileSystem

SEED = 0
EOT = "<|endoftext|>"
# (index, count): set by build_pool.py workers so each one streams a disjoint part of a dataset
SHARD = None
# adapter -> how many files `datasets` reads at once to fill a shuffle buffer (its default is 10).
# Set by build_pool.py; left empty, every build picks the same documents as before.
INPUT_SHARDS = {}


def _ds(*args, shuffle=False, buffer=20000, columns=None, input_shards=None, **kw):
    # read only the columns an adapter uses: Arrow batches and the shuffle buffer hold whole rows, and
    # Cosmopedia's long prompts nearly double a worker's memory (2.9 -> 1.5 GB). Parquet skips them on
    # read; a format without that option drops them after. Rows and their order do not change.
    try:
        ds = load_dataset(*args, streaming=True, **({"columns": columns} if columns else {}), **kw)
    except (TypeError, ValueError):
        ds = load_dataset(*args, streaming=True, **kw)
    if columns:
        ds = ds.select_columns(columns)
    if SHARD and SHARD[1] > 1:
        i, k = SHARD
        # whole files when there are enough of them, otherwise every k-th row (each worker
        # then downloads the full stream but only processes its rows)
        if ds.n_shards >= k:
            ds = ds.shard(num_shards=k, index=i)
        else:
            ds = ds.filter(lambda _, idx: idx % k == i, with_indices=True)
    if not shuffle:
        return ds
    if input_shards:
        return ds.shuffle(seed=SEED, buffer_size=buffer, max_buffer_input_shards=input_shards)
    return ds.shuffle(seed=SEED, buffer_size=buffer)


def _lines(path):
    with HfFileSystem().open(path, "r", encoding="utf-8", errors="replace") as f:
        yield from f


def tinystories(size):
    buf = []
    for line in _lines("datasets/roneneldan/TinyStories/TinyStoriesV2-GPT4-train.txt"):
        if EOT in line:
            text = " ".join(buf).strip()
            buf = []
            if text:
                # the source lost curly quotes as U+FFFD: between letters it was an apostrophe
                text = re.sub(r"(?<=\w)�(?=\w)", "'", text).replace("�", '"')
                yield {"text": text}
        else:
            buf.append(line.strip())


def simplestories(size):
    for r in _ds("SimpleStories/SimpleStories", split="train", shuffle=True, columns=["story"]):
        yield {"text": r["story"]}


def cosmo_stories(size):
    for r in _ds("HuggingFaceTB/cosmopedia", "stories", split="train", shuffle=True, columns=["text", "audience"]):
        yield {"text": r["text"], "audience": r.get("audience")}


def tinydialogues(size):
    for line in _lines("datasets/styfeng/TinyDialogues/tinydialogue_train_ordered.txt"):
        for doc in line.split(EOT):
            turns = []
            for t in doc.split("\\n\\n"):
                m = re.match(r'\s*\*\*(.+?)\*\*\s*:\s*(.+)', t.strip(), re.S)
                if m:
                    turns.append((m.group(1).strip(), m.group(2).strip().strip('"')))
            if turns:
                yield {"turns": turns}


def soda(size):
    for r in _ds("allenai/soda", split="train", shuffle=True, columns=["dialogue", "speakers"]):
        d, s = r["dialogue"], r["speakers"]
        d = ast.literal_eval(d) if isinstance(d, str) else d
        s = ast.literal_eval(s) if isinstance(s, str) else s
        if d and len(d) == len(s) and 4 <= len(d) <= 12:
            yield {"turns": list(zip(s, d))}


def _chat(msgs):
    names = {"user": "User", "assistant": "Assistant"}
    return [(names[m["role"]], m["content"]) for m in msgs if m["role"] in names]


def ultrachat(size):
    for r in _ds("HuggingFaceH4/ultrachat_200k", split="train_sft", shuffle=True, columns=["messages"]):
        yield {"turns": _chat(r["messages"])}


def smoltalk(size):
    # interleave the three configs so none is exhausted first
    its = [iter(_ds("HuggingFaceTB/smoltalk", c, split="train", shuffle=True, columns=["messages"]))
           for c in ("everyday-conversations", "smol-summarize", "smol-rewrite")]
    while its:
        for it in list(its):
            try:
                yield {"turns": _chat(next(it)["messages"])}
            except StopIteration:
                its.remove(it)


def tinyhelen(size):
    base = "hf://datasets/EmpathYang/TinyHelen/data/leaner/100M/train/"
    fs = HfFileSystem()
    files = sorted(p for p in fs.ls("datasets/EmpathYang/TinyHelen/data/leaner/100M/train", detail=False)
                   if any(k in p.split("/")[-1] for k in ("book", "conversation", "textbook", "web", "wiki")))
    streams = [iter(load_dataset("json", data_files=base + p.split("/")[-1], split="train", streaming=True))
               for p in files]
    # round-robin over the genre files so the mix is balanced
    while streams:
        for it in list(streams):
            try:
                yield {"text": next(it)["text"]}
            except StopIteration:
                streams.remove(it)


def simplewiki(size):
    for r in _ds("wikimedia/wikipedia", "20231101.simple", split="train", shuffle=True, columns=["text", "title"]):
        yield {"text": r["text"], "title": r["title"]}


def enwiki_intro(size):
    for r in _ds("wikimedia/wikipedia", "20231101.en", split="train", shuffle=True, columns=["text", "title"]):
        intro = r["text"].split("\n\n")[0]
        yield {"text": intro, "title": r["title"]}


def cosmo_v2(size):
    kids = {"young_children", "middle_school_students", "grade_school_students", "children"}
    for r in _ds("HuggingFaceTB/smollm-corpus", "cosmopedia-v2", split="train", shuffle=True,
                 columns=["text", "audience", "format"]):
        if size == "10M" and r["audience"] not in kids:
            continue
        yield {"text": r["text"], "audience": r["audience"], "format": r["format"]}


def cosmo_v01(size):
    its = [iter(_ds("HuggingFaceTB/cosmopedia", c, split="train", shuffle=True, columns=["text"]))
           for c in ("wikihow", "khanacademy", "openstax")]
    while its:
        for it in list(its):
            try:
                yield {"text": next(it)["text"]}
            except StopIteration:
                its.remove(it)


def tiny_textbooks(size):
    # `text` is raw web (RefinedWeb); `textbook` is the synthetic lesson we want
    for r in _ds("nampdn-ai/tiny-textbooks", split="train", shuffle=True, columns=["textbook"]):
        yield {"text": r["textbook"]}


def fineweb_edu(size):
    for r in _ds("HuggingFaceFW/fineweb-edu", "sample-10BT", split="train", columns=["text", "int_score"]):
        if r["int_score"] >= 4:
            yield {"text": r["text"]}


def gutenberg_books(size):
    # whole books per row: a 20k-row shuffle buffer overflows Arrow's 2 GB string offsets, and each
    # file decodes ~300 MB row groups, so reading 10 files at once peaks near 6 GB
    for r in _ds("manu/project_gutenberg", split="en", shuffle=True, buffer=8, columns=["text"],
                 input_shards=INPUT_SHARDS.get("gutenberg_books")):
        t = r["text"]
        a = re.search(r"\*\*\* ?START OF (THE|THIS) PROJECT GUTENBERG[^\n]*\n", t)
        b = re.search(r"\*\*\* ?END OF (THE|THIS) PROJECT GUTENBERG", t)
        if a:
            t = t[a.end():]
        if b:
            t = t[:t.rfind("*** END")] if "*** END" in t else t[:b.start()]
        paras = [re.sub(r"\s*\n\s*", " ", p).strip() for p in re.split(r"\n\s*\n", t)]
        paras = [p for p in paras if p and not (p.isupper() and len(p) < 80)]
        chunk, n = [], 0
        for p in paras:
            chunk.append(p)
            n += len(p.split())
            if n >= 300:
                yield {"text": "\n\n".join(chunk)}
                chunk, n = [], 0


def poetry(size):
    rng = random.Random(SEED)
    cur, lines, target = None, [], rng.randint(4, 20)
    for r in _ds("biglam/gutenberg-poetry-corpus", split="train", columns=["line", "gutenberg_id"]):
        if r["gutenberg_id"] != cur:
            cur, lines = r["gutenberg_id"], []
        lines.append(r["line"].strip())
        if len(lines) >= target:
            yield {"text": "\n".join(lines)}
            lines, target = [], rng.randint(4, 20)


def cnn(size):
    for r in _ds("abisee/cnn_dailymail", "3.0.0", split="train", shuffle=True, columns=["article", "highlights", "id"]):
        text = r["article"]
        if zlib.crc32(r["id"].encode()) % 10 < 3:
            text += "\n\nIn short: " + " ".join(r["highlights"].split("\n"))
        yield {"text": text}


REGISTRY = {f.__name__: f for f in (
    tinystories, simplestories, cosmo_stories, tinydialogues, soda, ultrachat, smoltalk,
    tinyhelen, simplewiki, enwiki_intro, cosmo_v2, cosmo_v01, tiny_textbooks, fineweb_edu,
    gutenberg_books, poetry, cnn)}