File size: 16,631 Bytes
4875150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env python3
"""
Truncation-Free, EOS-Verified, Position-Balanced Pure Apache-2.0 / MIT / CC0-1.0
Prompt-Compression Corpus Synthesizer (`Tamarillo/prompt-compression-corpus-2026` v3).

Fixes the positional tail-truncation bug discovered in v1/v2 (where max_new_tokens=220 truncated
220-word chunks at ~65%, causing 50% of docs to have all-zero tails):
  1. Uses clean <=130-word sentence-boundary chunks (~160-190 subword tokens).
  2. Sets `max_new_tokens = max(280, int(input_tokens * 1.15))` AND strictly requires EOS termination
     (generated token length < max_new_tokens) — ANY truncated generation is rejected!
  3. Enforces per-chunk positional balance (`tail_25_keep >= 0.15` and `|first_half - second_half| <= 0.40`)
     AND logs the exact 10-decile keep-rate curve in `corpus_summary_v3.json` to prove zero positional bias!
  4. Multi-rate prompting (50% target 40-50%, 50% target 55-68%) for smooth continuous token ranking.
"""
from __future__ import annotations

import argparse
import gc
import json
import random
import time
from collections import Counter
from pathlib import Path
from typing import Any

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import torch
import transformers.modeling_utils as _tmu
from transformers import AutoModelForCausalLM, AutoTokenizer

from synth_corpus_2026 import (
    WORD_RE,
    align_extractive_lcs,
    build_programmatic_logs,
    iter_parquet_rows,
    norm_hash,
    split_sentence_chunks,
)
from synth_corpus_v2 import collect_held_out_hashes

if getattr(_tmu, "ALL_PARALLEL_STYLES", None) is None:
    _tmu.ALL_PARALLEL_STYLES = {
        "colwise", "rowwise", "colwise_rep", "rowwise_rep",
        "sequence_parallel", "local_colwise", "local_rowwise", "local",
    }

PROMPT_RATE_45 = (
    "Compress the passage below into roughly 40% to 50% of its words by removing filler, articles, "
    "stopwords, and redundant phrasing evenly from the BEGINNING, MIDDLE, AND END.\n"
    "STRICT RULES:\n"
    "1. Copy kept words VERBATIM in their exact original order (never paraphrase or invent words).\n"
    "2. Compress ALL sentences evenly all the way to the very last sentence — NEVER stop early or truncate the end.\n"
    "3. Keep key nouns, entities, numbers, dates, negations, verbs, and JSON keys/values.\n"
    "4. Output ONLY the compressed text."
)

PROMPT_RATE_60 = (
    "Lightly compress the passage below into roughly 55% to 68% of its words by dropping filler and "
    "redundant words evenly across the BEGINNING, MIDDLE, AND END.\n"
    "STRICT RULES:\n"
    "1. Copy kept words VERBATIM in their exact original order (never paraphrase or invent words).\n"
    "2. Compress ALL sentences evenly all the way to the very last sentence — NEVER stop early or truncate the end.\n"
    "3. Preserve all factual entities, numbers, dates, negations, technical terms, and JSON keys/values.\n"
    "4. Output ONLY the compressed text."
)


def collect_fresh_docs(blocked_hashes: set[str], rng: random.Random) -> list[dict[str, Any]]:
    seen = set(blocked_hashes)
    docs: list[dict[str, Any]] = []

    def add_doc(text: str, domain: str, source_dataset: str, source_license: str, lang: str, min_w: int, max_w: int) -> bool:
        ws = WORD_RE.findall(str(text or ""))
        if len(ws) < min_w:
            return False
        clipped = " ".join(ws[:max_w])
        h = norm_hash(clipped)
        if h in seen:
            return False
        seen.add(h)
        docs.append({
            "text": clipped,
            "domain": domain,
            "source_dataset": source_dataset,
            "source_license": source_license,
            "lang": lang,
        })
        return True

    # 1. qiaojin/PubMedQA (MIT) -> 1,200 dense factual scientific passages
    c = 0
    for r in iter_parquet_rows("qiaojin/PubMedQA", "pqa_artificial/train-00000-of-00001.parquet", ["context"], limit=8000):
        if c >= 1200: break
        ctx_d = r.get("context") or {}
        ctxs = ctx_d.get("contexts", []) if isinstance(ctx_d, dict) else []
        if add_doc("\n\n".join(ctxs), "pubmedqa_scientific", "qiaojin/PubMedQA", "mit", "en", 100, 480):
            c += 1

    # 2. FiscalNote/billsum (CC0-1.0) -> 900 legislative/policy docs
    c = 0
    for r in iter_parquet_rows("FiscalNote/billsum", "data/train-00000-of-00001.parquet", ["text"], limit=6000):
        if c >= 900: break
        if add_doc(r.get("text", ""), "billsum_policy", "FiscalNote/billsum", "cc0-1.0", "en", 150, 520):
            c += 1

    # 3. OpenAssistant/oasst2 (Apache-2.0) -> 900 English technical/assistant passages
    c = 0
    for r in iter_parquet_rows("OpenAssistant/oasst2", "data/train-00000-of-00001-88ba0162028a73fc.parquet", ["text", "lang"], limit=40000):
        if c >= 900: break
        if str(r.get("lang", "")).lower() != "en": continue
        if add_doc(r.get("text", ""), "oasst2_dialogue", "OpenAssistant/oasst2", "apache-2.0", "en", 90, 480):
            c += 1

    # 4. HuggingFaceH4/ultrachat_200k (MIT) -> 800 technical QA passages
    c = 0
    try:
        for r in iter_parquet_rows("HuggingFaceH4/ultrachat_200k", "data/train_sft-00000-of-00003-a3ecf92756993583.parquet", ["messages"], limit=6000):
            if c >= 800: break
            msgs = r.get("messages") or []
            txt = "\n\n".join(str(m.get("content", "")) for m in msgs[:4] if isinstance(m, dict))
            if add_doc(txt, "ultrachat_dialogue", "HuggingFaceH4/ultrachat_200k", "mit", "en", 100, 480):
                c += 1
    except Exception as e:
        print(f"[warn] ultrachat skipped: {e}", flush=True)

    # 5. CohereLabs/aya_dataset (Apache-2.0) -> 1,100 multilingual passages (20+ langs)
    c = 0
    for r in iter_parquet_rows("CohereLabs/aya_dataset", "data/train-00000-of-00001.parquet", ["inputs", "targets", "language"], limit=60000):
        if c >= 1100: break
        lg = str(r.get("language", "")).lower()
        if not lg or lg == "english": continue
        txt = f"{r.get('inputs', '')}\n\n{r.get('targets', '')}"
        if add_doc(txt, "aya_multilingual", "CohereLabs/aya_dataset", "apache-2.0", lg, 70, 420):
            c += 1

    # 6. abisee/cnn_dailymail (Apache-2.0) -> 700 news articles
    c = 0
    for r in iter_parquet_rows("abisee/cnn_dailymail", "3.0.0/train-00000-of-00003.parquet", ["article"], limit=5000):
        if c >= 700: break
        if add_doc(r.get("article", ""), "cnn_dm_news", "abisee/cnn_dailymail", "apache-2.0", "en", 140, 500):
            c += 1

    # 7. Programmatic Agent JSON / Observability Logs (Apache-2.0) -> 700 structured logs
    for r in build_programmatic_logs(700, rng):
        add_doc(r["text"], r["domain"], r["source_dataset"], r["source_license"], r["lang"], 60, 450)

    rng.shuffle(docs)
    return docs


def compute_decile_curve(docs: list[dict[str, Any]]) -> list[float]:
    bins = [[] for _ in range(10)]
    for d in docs:
        lb = d["labels"]
        n = len(lb)
        if n < 20:
            continue
        for b in range(10):
            s, e = int(b * n / 10), int((b + 1) * n / 10)
            if e > s:
                bins[b].append(sum(lb[s:e]) / (e - s))
    return [round(float(np.mean(b)), 4) if b else 0.0 for b in bins]


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--teacher", type=str, default="Qwen/Qwen3-14B")
    parser.add_argument("--batch-size", type=int, default=128)
    parser.add_argument("--max-minutes", type=float, default=52.0)
    parser.add_argument("--out-dir", type=str, required=True)
    args = parser.parse_args()

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    rng = random.Random(2028)

    blocked = collect_held_out_hashes()
    docs = collect_fresh_docs(blocked, rng)
    print(f"[v3] Collected {len(docs):,} fresh pure commercial docs: {dict(Counter(d['domain'] for d in docs))}", flush=True)

    doc_to_chunks: dict[int, list[tuple[int, str, str]]] = {}
    total_flat = 0
    for doc_i, d in enumerate(docs):
        sys_p = PROMPT_RATE_45 if (doc_i % 2 == 0) else PROMPT_RATE_60
        # Short <=120-word chunks (~155 tok) ensure Qwen3-14B NEVER truncates and finishes cleanly at EOS!
        chs = split_sentence_chunks(d["text"], max_words=120)
        for ch_i, ch in enumerate(chs):
            if len(WORD_RE.findall(ch)) >= 20:
                doc_to_chunks.setdefault(doc_i, []).append((ch_i, ch, sys_p))
                total_flat += 1
    print(f"[v3] Flattened -> {total_flat:,} <=120w chunks across {len(doc_to_chunks):,} docs", flush=True)

    tok = AutoTokenizer.from_pretrained(args.teacher, padding_side="left")
    if tok.pad_token_id is None:
        tok.pad_token_id = tok.eos_token_id
    eos_ids = {tok.eos_token_id}
    if getattr(tok, "pad_token_id", None) is not None:
        eos_ids.add(tok.pad_token_id)

    model = AutoModelForCausalLM.from_pretrained(
        args.teacher, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
    ).to("cuda").eval()

    def build_prompt(txt: str, sys_p: str) -> str:
        msgs = [{"role": "system", "content": sys_p}, {"role": "user", "content": txt}]
        try:
            return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
        except TypeError:
            return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)

    t0 = time.perf_counter()
    deadline = t0 + args.max_minutes * 60.0
    aligned_docs: list[dict[str, Any]] = []
    total_chunks_done = 0
    total_chunks_passed = 0
    total_chunks_eos_trunc = 0
    total_chunks_pos_rej = 0
    wave_size = 600
    doc_ids = list(doc_to_chunks.keys())

    for w_start in range(0, len(doc_ids), wave_size):
        if time.perf_counter() >= deadline:
            print(f"  [TIME CAP] Reached {args.max_minutes}m after {len(aligned_docs)} clean docs. Stopping cleanly.", flush=True)
            break
        w_doc_ids = doc_ids[w_start : w_start + wave_size]
        w_items = [(di, ci, ch, sp) for di in w_doc_ids for (ci, ch, sp) in doc_to_chunks[di]]
        w_order = sorted(range(len(w_items)), key=lambda idx: len(w_items[idx][2]))
        w_prompts = [build_prompt(w_items[idx][2], w_items[idx][3]) for idx in w_order]
        w_comp = [""] * len(w_items)
        w_hit_cap = [False] * len(w_items)

        for i in range(0, len(w_order), args.batch_size):
            idxs = w_order[i : i + args.batch_size]
            enc = tok(w_prompts[i : i + args.batch_size], padding=True, truncation=True, max_length=640, return_tensors="pt").to("cuda")
            in_len = enc["input_ids"].shape[1]
            # Generous headroom: NEVER truncate mid-chunk!
            max_new = 300
            with torch.inference_mode():
                gen = model.generate(**enc, max_new_tokens=max_new, do_sample=False, pad_token_id=tok.pad_token_id)
            gen_new = gen[:, in_len:]
            decoded = tok.batch_decode(gen_new, skip_special_tokens=True)
            for row_j, (k, d_txt) in enumerate(zip(idxs, decoded)):
                # Check whether sequence emitted EOS before hitting max_new
                last_tok = int(gen_new[row_j, -1].item())
                hit_cap = (gen_new.shape[1] >= max_new) and (last_tok not in eos_ids)
                w_hit_cap[k] = hit_cap
                w_comp[k] = d_txt.strip()

        by_doc_res: dict[int, list[tuple[int, list[str], list[int], float, float]]] = {}
        for idx, ((di, ci, orig_ch, _sp), comp_ch) in enumerate(zip(w_items, w_comp)):
            total_chunks_done += 1
            if w_hit_cap[idx]:
                total_chunks_eos_trunc += 1
                continue
            ow, cw = WORD_RE.findall(orig_ch), WORD_RE.findall(comp_ch)
            labels, fid = align_extractive_lcs(ow, cw)
            n = len(ow)
            ret = sum(labels) / max(n, 1)
            if not (fid >= 0.90 and 0.22 <= ret <= 0.85):
                continue
            # Strict positional-balance gate: tail 25% must retain >= 0.15 and halves balanced!
            q = max(4, n // 4)
            tail_r = sum(labels[-q:]) / q
            first_h = sum(labels[: n // 2]) / max(n // 2, 1)
            second_h = sum(labels[n // 2 :]) / max(n - n // 2, 1)
            if tail_r < 0.15 or abs(first_h - second_h) > 0.35:
                total_chunks_pos_rej += 1
                continue
            total_chunks_passed += 1
            by_doc_res.setdefault(di, []).append((ci, ow, labels, fid, ret))

        for di in w_doc_ids:
            orig_n = len(doc_to_chunks[di])
            res_list = sorted(by_doc_res.get(di, []), key=lambda x: x[0])
            if not res_list or len(res_list) < orig_n:
                # Require ALL chunks of a doc to pass so no document has missing tail chunks!
                continue
            all_words: list[str] = []
            all_labels: list[int] = []
            for _, ow, lb, _, _ in res_list:
                all_words.extend(ow)
                all_labels.extend(lb)
            mean_fid = float(np.mean([x[3] for x in res_list]))
            doc_ret = sum(all_labels) / max(len(all_words), 1)
            dmeta = docs[di]
            aligned_docs.append({
                "doc_id": f"tamarillo_pc_v3_{len(aligned_docs):06d}",
                "text": " ".join(all_words),
                "compressed_text": " ".join(w for w, lb in zip(all_words, all_labels) if lb == 1),
                "words": all_words,
                "labels": all_labels,
                "n_words": len(all_words),
                "n_kept": int(sum(all_labels)),
                "retention_ratio": round(doc_ret, 4),
                "lcs_fidelity": round(mean_fid, 4),
                "domain": dmeta["domain"],
                "lang": dmeta["lang"],
                "source_dataset": dmeta["source_dataset"],
                "source_license": dmeta["source_license"],
                "teacher_model": args.teacher,
            })

        el = time.perf_counter() - t0
        cpm = total_chunks_done / max(el / 60.0, 1e-6)
        dec = compute_decile_curve(aligned_docs)
        print(
            f"  [Wave {w_start + len(w_doc_ids):4d}/{len(doc_ids)}] chunks={total_chunks_done:,} "
            f"(pass={total_chunks_passed/max(total_chunks_done,1)*100:.1f}%, eos_trunc={total_chunks_eos_trunc}, pos_rej={total_chunks_pos_rej}) "
            f"docs={len(aligned_docs):,} speed={cpm:.1f} ch/m deciles={dec}",
            flush=True,
        )

    synth_sec = time.perf_counter() - t0
    del model; gc.collect(); torch.cuda.empty_cache()

    rng.shuffle(aligned_docs)
    n_val = max(250, int(0.05 * len(aligned_docs)))
    val_docs = aligned_docs[:n_val]
    tr_docs = aligned_docs[n_val:]

    data_dir = out_dir / "parquet"
    data_dir.mkdir(parents=True, exist_ok=True)
    pq.write_table(pa.Table.from_pylist(tr_docs), data_dir / "train-00000-of-00001.parquet")
    pq.write_table(pa.Table.from_pylist(val_docs), data_dir / "validation-00000-of-00001.parquet")

    deciles = compute_decile_curve(aligned_docs)
    summary = {
        "version": "v3_eos_verified_position_balanced",
        "teacher": args.teacher,
        "total_docs_kept": len(aligned_docs),
        "train_docs": len(tr_docs),
        "val_docs": len(val_docs),
        "total_chunks_processed": total_chunks_done,
        "total_chunks_passed": total_chunks_passed,
        "total_chunks_eos_truncated_rejected": total_chunks_eos_trunc,
        "total_chunks_pos_imbalanced_rejected": total_chunks_pos_rej,
        "chunk_pass_rate": round(total_chunks_passed / max(total_chunks_done, 1), 4),
        "synth_minutes": round(synth_sec / 60.0, 2),
        "chunks_per_min": round(total_chunks_done / max(synth_sec / 60.0, 1e-6), 1),
        "mean_doc_words": round(float(np.mean([d["n_words"] for d in aligned_docs])), 1) if aligned_docs else 0.0,
        "mean_retention": round(float(np.mean([d["retention_ratio"] for d in aligned_docs])), 4) if aligned_docs else 0.0,
        "mean_lcs_fidelity": round(float(np.mean([d["lcs_fidelity"] for d in aligned_docs])), 4) if aligned_docs else 0.0,
        "keep_rate_by_decile_0_to_9": deciles,
        "by_domain": dict(Counter(d["domain"] for d in aligned_docs)),
        "by_license": dict(Counter(d["source_license"] for d in aligned_docs)),
        "n_languages": len({d["lang"] for d in aligned_docs}),
    }
    (out_dir / "corpus_summary_v3.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print("\n=== CORPUS V3 (EOS-VERIFIED & POSITION-BALANCED) COMPLETE ===")
    print(json.dumps(summary, indent=2), flush=True)


if __name__ == "__main__":
    main()