File size: 11,869 Bytes
c9a0484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the dataset bundle of the texts behind "Fine Until Fine-Tuned" from a DuraSeed-v1 checkout.

    python build_bundle.py --duraseed <DuraSeed-v1 checkout> --out <bundle folder>

It takes the files the code repository's src/collect.py reads to build outputs/, and the training texts those
runs trained on, and writes them under <out>/runs/ at the same relative paths: JSON files gzipped (.jsonl.gz,
and .json.gz for the clone corpus's 800 group files), score arrays (.npz) and the small id lists of the
training order (.json) as they are. What changes:

- `prompt_token_ids` is dropped from the math training files: it is the tokenized third-party problem
  (NuminaMath-TIR) or chat prompt (Tulu 3 mixture), which the repository's src/build_inputs.py rebuilds by id;
- the habit file's responses to WildJailbreak and WildGuardMix prompts are withheld; their ids and sources are
  listed in habit_withheld.jsonl.gz beside it;
- where a model's output is stored only as token ids, the decoded text is added beside them (`text`,
  `sample_texts`, `generation.completion_text`), decoded as the repository's common.models.Family does:
  Qwen3.5-9B-Base's tokenizer for the Qwen runs, Nemotron-3 Nano's for main-nemotron-20260924;
- the Tinker checkpoint URIs (they hold session ids) are dropped from the clone corpus.

Every other JSON-lines file is compressed byte for byte. It then writes MANIFEST.csv (every file, with the
LoRA adapters and Tinker states that are not included) and TOTALS.csv (per run). Needs numpy and transformers,
with both tokenizers in the local Hugging Face cache.
"""

import argparse
import csv
import gzip
import hashlib
import json
import os
from contextlib import contextmanager
from concurrent.futures import ProcessPoolExecutor
from functools import lru_cache
from pathlib import Path

import numpy as np

os.environ["HF_HUB_OFFLINE"] = "1"
MATH_RUNS = ("pilot-20260924", "main-9b-20260924", "main-35b-20260924", "main-nemotron-20260924", "teacher-20260924",
             "robustness-20260924", "robustness-followup-20260924", "revision-rp-20260926", "revision-rs-20260926",
             "revision-rl-20260926", "revision-sh-20260926", "revision-sd-20260926/s2", "revision-sd-20260926/s3")
TCES_KINDS = ("decision", "think", "competence", "unforced")
SKILL_SETS = ("smoke-cap4096", "smoke-cap8192", "smoke-cap2048", "calibration", "eval")
MATH_TEXTS = ("rft.jsonl", "p_samples.jsonl", "sharp-t05.jsonl", "habit.jsonl")  # training texts, prompts dropped
ORDER = ("arms.json", "d2.json", "replayed.json", "calibration.json")  # training order and choices: ids only
PROMPT = ("prompt_token_ids",)
WITHHELD = ("ai2-adapt-dev/tulu_v3.9_wildjailbreak_decontaminated_50k",
            "ai2-adapt-dev/tulu_v3.9_synthetic_finalresp_wildguardmixtrain_decontaminated_50k")
CORPUS = "endpoint-clone/endpoint-clone-20260910T162817Z/acquisition/corpus"
URIS = ("sampler_path", "sampler_checkpoint_path", "origin_sampler_checkpoint_path")  # Tinker URIs
ADAPTERS = "artifacts/endpoint-clone/endpoint-clone-20260910T162817Z/adapters"
QWEN, NEMOTRON = "Qwen/Qwen3.5-9B-Base", "nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16"
NOTES = {"prompt": "prompt_token_ids removed (third-party prompt); decoded text added",
         "text": "decoded text added",
         "withheld": "ids of the withheld habit rows, no text",
         "corpus": "Tinker checkpoint URIs removed",
         "absent": "not included, available on request"}


def dirs(root):
    return sorted(p for p in root.glob("*") if p.is_dir())


def plan(runs):
    """(source, kind) for every file of the bundle; kind is copy, jsonl, text, prompt or corpus."""
    files = []
    probes = [d for d in dirs(runs / "decision-probe") if d.name != "dc-20260923"]  # dc-20260923 was aborted
    for run in probes + dirs(runs / "repetition-probe") + [runs / "anchor/anchor-20260924"]:
        files += [(p, "jsonl") for p in sorted(run.glob("*/u*/*.jsonl")) if p.stem in TCES_KINDS]
    anchor = runs / "anchor/anchor-20260924"
    files += [(anchor / "anchor.jsonl", "text"), (anchor / "anchor.partial.jsonl", "text")]  # M0's own samples
    for root in (anchor, runs / "depth-profile/depth-20260923", runs / "depth-profile/depth-full-20260924"):
        files += [(p, "copy") for p in sorted(root.rglob("*.npz"))]
    for name in MATH_RUNS:
        root = runs / "math" / name
        files += [(p, "jsonl") for p in sorted(root.glob("eval/*/*/*.jsonl")) if ".partial" not in p.name]
        files += [(p, "jsonl") for p in sorted(root.glob("reforce/*/*/*-forced.jsonl"))]
        files += [(p, "text") for p in sorted(root.glob("depth/*/texts.jsonl"))]
        files += [(p, "copy") for p in sorted(root.rglob("*.npz"))]
        files += [(root / f, "prompt") for f in MATH_TEXTS if (root / f).exists()]
        files += [(p, "jsonl") for p in [root / "teacher/traces.jsonl"] if p.exists()]
        files += [(root / f, "copy") for f in ORDER if (root / f).exists()]
    files += [(p, "corpus") for p in sorted((runs / CORPUS).glob("group-*/samples.json"))]  # TCES training texts
    skill = runs / "skill/skill-20260926"
    files += [(p, "jsonl") for group in SKILL_SETS for p in sorted((skill / group).glob("*.jsonl"))]
    files += [(skill / f, "copy") for f in ORDER if (skill / f).exists()]
    return files


@lru_cache
def tokenizer(model):
    """The tokenizer as common.models.Family loads it."""
    from transformers import AutoTokenizer
    if model == NEMOTRON:
        cache = Path("~/.cache/huggingface/hub/models--nvidia--NVIDIA-Nemotron-3-Nano-30B-A3B-BF16").expanduser()
        return AutoTokenizer.from_pretrained(str(sorted(cache.glob("snapshots/*"))[0]))
    return AutoTokenizer.from_pretrained(model)


def with_text(r, decode):
    """The row with the decoded text beside each list of token ids the model wrote."""
    out = {}
    for key, value in r.items():
        out[key] = with_text(value, decode) if key == "generation" and value else value
        if key in ("token_ids", "completion_token_ids"):
            out["text" if key == "token_ids" else "completion_text"] = decode(value)
        elif key == "samples":
            out["sample_texts"] = [decode(s) for s in value]
    return out


@contextmanager
def gz(path):
    """A gzip writer with no name or time in its header, so that a rebuild is byte-identical."""
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("wb") as raw, gzip.GzipFile(filename="", mode="wb", fileobj=raw, compresslevel=6, mtime=0) as w:
        yield w


def sha256(path):
    h = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def dump(row):
    return (json.dumps(row, ensure_ascii=False) + "\n").encode()


def build(job):
    """Write one bundle file (and the habit file's list of withheld rows); returns their manifest rows."""
    source, kind, runs, out = job
    target, rows, withheld = out / "runs" / source.relative_to(runs), None, []
    if kind == "corpus":  # one group of the clone corpus: a JSON object holding 8 samples
        group = {k: v for k, v in json.loads(source.read_text()).items() if k not in URIS}
        for r in group["records"]:
            r["generation"] = {k: v for k, v in r["generation"].items() if k not in URIS}
        target, rows = target.with_name(target.name + ".gz"), len(group["records"])
        with gz(target) as w:
            w.write(json.dumps(group).encode())
    elif kind == "copy":
        target.parent.mkdir(parents=True, exist_ok=True)
        target.write_bytes(source.read_bytes())
        rows = len(np.load(target)["task_ids"]) if source.suffix == ".npz" else None
    else:
        decode = tokenizer(NEMOTRON if "/math/main-nemotron-20260924/" in str(source) else QWEN).decode
        target, rows = target.with_name(target.name + ".gz"), 0
        with source.open("rb") as f, gz(target) as w:
            for i, line in enumerate(f):
                r = json.loads(line)  # every source line parses (a cut line would stop the build)
                chat = r.get("id", "").rsplit("_", 1)[0]
                if chat in WITHHELD:
                    withheld.append(dict(row=i, id=r["id"], source=chat))
                    continue
                if kind in ("text", "prompt"):
                    line = dump(with_text({k: v for k, v in r.items() if k not in PROMPT}, decode))
                w.write(line)
                rows += 1
    made = [dict(path=str(target.relative_to(out)), rows=rows, bytes=target.stat().st_size, sha256=sha256(target),
                 note=NOTES.get(kind, ""), source_bytes=source.stat().st_size)]
    if withheld:
        listed = target.with_name("habit_withheld.jsonl.gz")
        with gz(listed) as w:
            w.writelines(dump(x) for x in withheld)
        made.append(dict(path=str(listed.relative_to(out)), rows=len(withheld), bytes=listed.stat().st_size,
                         sha256=sha256(listed), note=NOTES["withheld"], source_bytes=0))
        made[0]["note"] += f"; {len(withheld)} rows withheld (WildJailbreak, WildGuardMix prompts)"
    return made


def absent(duraseed):
    """Manifest rows for what the bundle leaves out: the clone run's LoRA adapters and the Tinker states."""
    out = []
    for folder in sorted(p for p in (duraseed / ADAPTERS).glob("*") if p.is_dir()):
        for name in ("adapter_config.json", "adapter_model.safetensors"):
            path = folder / name
            out.append(dict(path=str(path.relative_to(duraseed)), rows=None, bytes=path.stat().st_size,
                            sha256=sha256(path), note=NOTES["absent"]))
    out.append(dict(path="tinker-states (the 86 listed in the code repository's data/checkpoints.json)", rows=86,
                    bytes=None, sha256=None, note="not included, archived on the author's Tinker account, "
                                                  "available on request"))
    return out


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--duraseed", type=Path, required=True, help="the DuraSeed-v1 checkout holding runs/")
    parser.add_argument("--out", type=Path, required=True, help="the bundle folder")
    args = parser.parse_args()
    duraseed, out = args.duraseed.resolve(), args.out.resolve()
    runs = duraseed / "runs"
    jobs = [(p, kind, runs, out) for p, kind in plan(runs)]
    with ProcessPoolExecutor() as pool:
        made = sorted((m for ms in pool.map(build, jobs, chunksize=1) for m in ms), key=lambda m: m["path"])
    with (out / "MANIFEST.csv").open("w", newline="") as f:
        w = csv.DictWriter(f, ("path", "rows", "bytes", "sha256", "note"), extrasaction="ignore")
        w.writeheader()
        w.writerows(made + absent(duraseed))
    totals = {}
    for m in made:  # per run: runs/<family>/<run>/...
        group = "/".join(m["path"].split("/")[1:3])
        t = totals.setdefault(group, dict(group=group, files=0, rows=0, source_bytes=0, bundle_bytes=0))
        t["files"], t["rows"] = t["files"] + 1, t["rows"] + (m["rows"] or 0)
        t["source_bytes"], t["bundle_bytes"] = t["source_bytes"] + m["source_bytes"], t["bundle_bytes"] + m["bytes"]
    total = dict(group="total", **{k: sum(t[k] for t in totals.values())
                                    for k in ("files", "rows", "source_bytes", "bundle_bytes")})
    with (out / "TOTALS.csv").open("w", newline="") as f:
        w = csv.DictWriter(f, ("group", "files", "rows", "source_bytes", "bundle_bytes"))
        w.writeheader()
        w.writerows([totals[k] for k in sorted(totals)] + [total])
    print(f"{total['files']} files, {total['rows']:,} rows (npz: texts), "
          f"{total['source_bytes'] / 1e9:.2f} GB -> {total['bundle_bytes'] / 1e9:.2f} GB")


if __name__ == "__main__":
    main()