File size: 6,263 Bytes
6a284b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build longctx30.jsonl: 30 long-context prompts from public-domain nonfiction.

Shape per record:
  id, workload ("10k"), task (one of five), source, article_ids (two),
  input_tokens (10000), max_out (1500), prompt

Each prompt is an intro line, two ~5k-token passages from two different books
under an ARTICLE header, then one of five task instructions. Tokens counted
with tiktoken o200k_base, the same tokenizer the benchmark client uses.

Source texts are Project Gutenberg plain-text editions. Run:
    python3 make_longctx_dataset.py --src ./gutenberg --out longctx30.jsonl
where ./gutenberg holds pg<ID>.txt files for the IDs in BOOKS.
"""
import argparse
import json
import re
from pathlib import Path

import tiktoken

ENC = tiktoken.get_encoding("o200k_base")

# Gutenberg ID -> short label. All public domain, all nonfiction prose.
BOOKS = {
    1228:  "darwin-origin",
    1404:  "federalist",
    15399: "equiano-narrative",
    944:   "darwin-beagle",
    205:   "thoreau-walden",
    23:    "douglass-narrative",
    2707:  "herodotus-histories",
    3300:  "smith-wealth-of-nations",
    34901: "mill-on-liberty",
    4367:  "grant-memoirs",
    674:   "plutarch-lives",
    7142:  "thucydides-peloponnesian",
}
CHUNKS_PER_BOOK = 5           # 12 books x 5 = 60 passages = 30 prompts x 2
TOKENS_PER_CHUNK = 5000
N_PROMPTS = 30

INTRO = "Read the following article carefully, then complete the task that follows.\n\n"
TASKS = [
    ("summarize",
     "Write a comprehensive, structured summary of the article above. Cover every major section, preserve key names, dates, and figures, and organize the summary with clear headings and bullet points. Aim for approximately 1500 tokens of output. Do not stop early.\n"),
    ("qa",
     "Based solely on the article above, produce a detailed Q&A study guide. Generate at least 20 question/answer pairs that together cover the full breadth of the article, including obscure details. Each answer should be a full paragraph. Aim for approximately 1500 tokens total. Do not stop early.\n"),
    ("extract_facts",
     "Extract a long, exhaustive list of factual claims from the article above. For each fact, write one sentence stating the fact and a second sentence giving the surrounding context. Produce at least 60 facts. Aim for approximately 1500 tokens total. Do not stop early.\n"),
    ("outline",
     "Produce a deeply nested outline (at least 4 levels deep) of the article above. Every leaf node must include a one-sentence explanation. Aim for approximately 1500 tokens of output. Do not stop early.\n"),
    ("rewrite",
     "Rewrite the article above in clear, modern, encyclopedic English suitable for a general audience. Preserve all factual content and section ordering. Aim for approximately 1500 tokens of output. Do not stop early.\n"),
]


def strip_gutenberg(text: str) -> str:
    """Drop the Gutenberg license header/footer, keep the work itself."""
    text = text.replace("\r\n", "\n")
    m = re.search(r"\*\*\* ?START OF (?:THE|THIS) PROJECT GUTENBERG EBOOK[^\n]*\n", text, re.I)
    if m:
        text = text[m.end():]
    m = re.search(r"\*\*\* ?END OF (?:THE|THIS) PROJECT GUTENBERG EBOOK", text, re.I)
    if m:
        text = text[: m.start()]
    # collapse runs of blank lines, unwrap hard-wrapped paragraphs
    paras = re.split(r"\n\s*\n", text)
    paras = [re.sub(r"\s+", " ", p).strip() for p in paras]
    paras = [p for p in paras if p]
    return "\n\n".join(paras)


def chunk_book(text: str, n: int, size: int) -> list[str]:
    """n passages of ~size tokens, evenly spaced through the book, cut on whitespace."""
    toks = ENC.encode(text)
    total = len(toks)
    assert total > n * size, f"book too short: {total} tokens"
    # Skip the first 6% (contents, prefaces, edition notes) and the last 8%
    # (indexes, appendices, notes). Space the passages evenly in between.
    first = int(total * 0.06)
    last_start = int(total * 0.92) - size
    stride = (last_start - first) // (n - 1) if n > 1 else 0
    out = []
    for i in range(n):
        s = first + i * stride
        piece = ENC.decode(toks[s : s + size])
        # trim to whitespace at both ends so we don't start or end mid-word
        piece = piece[piece.find(" ") + 1 :] if " " in piece[:40] else piece
        piece = piece[: piece.rfind(" ")] if " " in piece[-40:] else piece
        out.append(piece.strip())
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--src", default="gutenberg", help="dir with pg<ID>.txt files")
    ap.add_argument("--out", default="longctx30.jsonl")
    args = ap.parse_args()

    src = Path(args.src)
    passages = []  # (book_label, chunk_idx, text)
    for gid, label in BOOKS.items():
        p = src / f"{gid}.txt"
        if not p.exists():
            p = src / f"pg{gid}.txt"
        raw = p.read_text(encoding="utf-8", errors="replace")
        body = strip_gutenberg(raw)
        for ci, ch in enumerate(chunk_book(body, CHUNKS_PER_BOOK, TOKENS_PER_CHUNK)):
            passages.append((label, ci, ch))

    assert len(passages) == 2 * N_PROMPTS, len(passages)

    # Pair passage k with passage k+30. With 5 chunks/book in book order,
    # index k and k+30 always land on different books (30 = 6 books apart).
    rows = []
    for i in range(N_PROMPTS):
        a = passages[i]
        b = passages[i + N_PROMPTS]
        assert a[0] != b[0], (a[0], b[0])
        task, instr = TASKS[i % len(TASKS)]
        article = a[2] + "\n\n" + b[2]
        prompt = f"{INTRO}--- ARTICLE ---\n{article}\n--- TASK ---\n{instr}"
        rows.append({
            "id": f"10k-pd-{i:03d}",
            "workload": "10k",
            "task": task,
            "source": "gutenberg",
            "article_ids": [f"{a[0]}:{a[1]}", f"{b[0]}:{b[1]}"],
            "input_tokens": 10000,
            "max_out": 1500,
            "prompt": prompt,
        })

    with open(args.out, "w") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    lens = [len(ENC.encode(r["prompt"])) for r in rows]
    print(f"wrote {args.out}: {len(rows)} prompts, "
          f"prompt tokens min {min(lens)} median {sorted(lens)[len(lens)//2]} max {max(lens)}")


if __name__ == "__main__":
    main()