File size: 8,013 Bytes
c9faf30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Move the flat DeepSeek-era corpus into the pool, losslessly.

    python tools/pool_import.py

`calib_train.txt` was written by `pipeline/build.py` as documents joined with a
blank line, in ascending `id` order, and `calib_train.manifest.jsonl` records
each document's character count in that same order.  That makes the split exact
rather than heuristic: this script asserts the reconstruction re-joins to the
original file byte for byte and refuses to write anything if it does not.

Nothing at the repository root is modified.  `calib_heldout.txt` is deliberately
*not* imported: it is a measurement split, and putting it in the pool would let
a later build calibrate on it.
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import poollib as P

# legacy domain -> (pool category, subdirectory, shard name, synthetic)
DOMAIN_MAP = {
    "code":        ("code",         "",           "legacy-dsv4",           False),
    "graphics":    ("graphics",     "",           "legacy-dsv4",           False),
    "structured":  ("structured",   "",           "legacy-dsv4",           False),
    "longctx":     ("longctx",      "",           "legacy-dsv4",           False),
    "general":     ("multilingual", "",           "legacy-dsv4-wikipedia", False),
    "agentic":     ("agentic",      "synthetic",  "legacy-dsv4-rendered",  True),
    "reasoning":   ("reasoning",    "synthetic",  "legacy-dsv4-rendered",  True),
    "vocab_sweep": ("vocab_sweep",  "synthetic",  "legacy-dsv4-rendered",  True),
}

# Domains whose text is DeepSeek chat markup.  Kept for provenance, never
# usable as calibration for another model: the markup would tokenise as literal
# punctuation and calibrate nothing the target model ever emits.
DSV4_RENDERED = {"agentic", "reasoning"}

# vocab_sweep is a function of the tokenizer, not a corpus.  The DeepSeek sweep
# is kept but a build regenerates its own.
TOKENIZER_BOUND = {"vocab_sweep"}


def split_flat(txt_path: str, manifest_path: str) -> list[tuple[dict, str]]:
    recs = [json.loads(l) for l in open(manifest_path, encoding="utf-8") if l.strip()]
    if recs != sorted(recs, key=lambda r: r["id"]):
        raise SystemExit(f"{manifest_path}: not in ascending id order; "
                         "the offset reconstruction assumes pipeline/build.py ordering")
    text = open(txt_path, encoding="utf-8").read()
    out, pos = [], 0
    for i, r in enumerate(recs):
        doc = text[pos:pos + r["chars"]]
        pos += r["chars"]
        if i < len(recs) - 1:
            if text[pos:pos + 2] != "\n\n":
                raise SystemExit(f"{txt_path}: expected blank-line separator after "
                                 f"document {i} ({r['id']}), found {text[pos:pos+4]!r}")
            pos += 2
    # the writer appended a single trailing newline
        out.append((r, doc))
    if text[pos:] != "\n":
        raise SystemExit(f"{txt_path}: unexpected trailing bytes {text[pos:][:40]!r}")
    rejoined = "\n\n".join(d for _, d in out) + "\n"
    if rejoined != text:
        raise SystemExit(f"{txt_path}: reconstruction is not byte-identical")
    return out


def git_sha(repo_root: str) -> str:
    try:
        return subprocess.run(["git", "-C", repo_root, "rev-parse", "HEAD"],
                              capture_output=True, text=True, check=True).stdout.strip()
    except Exception:
        return "unknown"


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--repo", default=P.REPO_ROOT)
    args = ap.parse_args()
    root = args.repo
    sha = git_sha(root)

    train = split_flat(os.path.join(root, "calib_train.txt"),
                       os.path.join(root, "calib_train.manifest.jsonl"))
    print(f"calib_train.txt  -> {len(train)} documents, reconstruction byte-identical")

    buckets: dict[str, list[P.Record]] = {}
    unmapped: list[dict] = []
    for r, text in train:
        dom = r["domain"]
        if dom not in DOMAIN_MAP:
            unmapped.append(r)
            continue
        cat, sub, shard, synth = DOMAIN_MAP[dom]
        render = "dsv4" if dom in DSV4_RENDERED else "text"
        prov = {
            "imported_from": "calib_train.txt",
            "import_commit": sha,
            "legacy_domain": dom,
            "legacy_content_domain": r.get("content_domain", dom),
            "legacy_id": r["id"],
            "legacy_tokens_deepseek_v4": r.get("tokens", 0),
            "legacy_split": r.get("split", "calib_train"),
        }
        if dom in DSV4_RENDERED:
            prov["excluded_from_builds"] = (
                "text is rendered in DeepSeek-V4 chat markup (<|DSML|...>, "
                "<|User|>, <think>); those byte sequences are not special tokens "
                "for any other tokenizer. The equivalent conversations are "
                "regenerated structurally by tools/gen_agentic.py and "
                "tools/gen_reasoning.py.")
        if dom in TOKENIZER_BOUND:
            prov["excluded_from_builds"] = (
                "a vocabulary sweep is a function of the tokenizer it was built "
                "for (DeepSeek-V4, 129,280 rows). tools/vocab_sweep.py "
                "regenerates it for the target model.")
        rec = P.Record(
            category=cat, domain=dom, source=r["source"], license=r["license"],
            license_url="", path=r["path"], lang=r["lang"], origin=r["origin"],
            text=text, synthetic=synth, render=render, provenance=prov,
        )
        key = os.path.join(cat, sub, shard + ".jsonl") if sub else os.path.join(cat, shard + ".jsonl")
        buckets.setdefault(key, []).append(rec)

    if unmapped:
        # Never dropped: anything without a mapping lands in pool/unsorted with
        # the reason attached, so it can be triaged rather than lost.
        recs = []
        for r, text in train:
            if r in unmapped:
                recs.append(P.Record(
                    category="unsorted", domain=r["domain"], source=r["source"],
                    license=r["license"], path=r["path"], lang=r["lang"],
                    origin=r["origin"], text=text,
                    provenance={"imported_from": "calib_train.txt",
                                "import_commit": sha,
                                "reason": f"legacy domain {r['domain']!r} has no pool category"},
                ))
        buckets["unsorted/legacy-dsv4-unmapped.jsonl"] = recs

    total = 0
    for key in sorted(buckets):
        n = P.write_jsonl(os.path.join(P.POOL_ROOT, key), buckets[key])
        chars = sum(len(r.text) for r in buckets[key])
        total += n
        print(f"  pool/{key:52} {n:5} docs  {chars:9,} chars")
    print(f"  {total} documents written, {len(unmapped)} unmapped")

    # eval_neutral is copied into eval/neutral with provenance attached; the
    # file at the repository root is left exactly as it is because the existing
    # measurements are keyed to it.
    ev = split_flat(os.path.join(root, "eval_neutral.txt"),
                    os.path.join(root, "eval_neutral.manifest.jsonl"))
    erecs = [P.Record(
        category="code", domain=r["domain"], source=r["source"],
        license=r["license"], license_url="", path=r["path"], lang=r["lang"],
        origin=r["origin"], text=text,
        provenance={"imported_from": "eval_neutral.txt", "import_commit": sha,
                    "legacy_id": r["id"],
                    "note": "the flat file was renamed to eval/code/eval_code.txt and kept "
                            "byte-identical; measurement showed it is a code corpus, not "
                            "neutral prose. This is a categorised copy with provenance"},
    ) for r, text in ev]
    n = P.write_jsonl(os.path.join(P.EVAL_ROOT, "code", "eval-code-legacy.jsonl"), erecs)
    print(f"eval_neutral.txt -> eval/code/eval-code-legacy.jsonl  {n} docs")
    return 0


if __name__ == "__main__":
    sys.exit(main())