File size: 17,583 Bytes
bad1d0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/env python3
"""
Scale Pure Apache-2.0 / MIT / CC0-1.0 Extractive Prompt-Compression Dataset
(`Tamarillo/prompt-compression-corpus-2026` v2) from 1,550 -> ~5,000-6,000+ docs!

Upgrades over v1:
  - Multi-rate teacher prompting (50% target 40-55% aggressive, 50% target 60-75% gentle) so
    downstream token classifiers learn smooth, well-calibrated continuous token importance rankings!
  - Adds `HuggingFaceH4/ultrachat_200k` (MIT) technical/coding dialogues alongside `billsum`,
    `PubMedQA`, `oasst2`, `aya_dataset` (20+ langs), `cnn_dailymail`, and programmatic JSON logs.
  - Merges cleanly with existing 1,550 docs from `Tamarillo/prompt-compression-corpus-2026` (zero dupes).
  - Strict SHA256 zero-leakage exclusion against ALL 5 zero-touch eval suites
    (`hotpot_qa`, `squad_v2`, `gsm8k`, `xquad`, `mbpp`).
"""
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 huggingface_hub import hf_hub_download
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,
)

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_AGGRESSIVE = (
    "You are a precise extractive prompt compressor. Compress the user's passage by keeping ONLY the "
    "essential words verbatim in their exact original order so a downstream AI can answer any factual, "
    "numerical, or structural question accurately.\n"
    "RULES:\n"
    "1. Copy words strictly verbatim from the input in original order. NEVER paraphrase, rewrite, or add new words.\n"
    "2. Target keeping roughly 40% to 55% of the original words evenly across the passage.\n"
    "3. Always preserve key entities, names, dates, numbers, negations, technical terms, and JSON/code keys & values.\n"
    "4. Output ONLY the compressed text — no preamble, no explanations, no markdown fences."
)

PROMPT_GENTLE = (
    "You are a precise extractive prompt compressor. Lightly compress the user's passage by removing filler, "
    "redundancy, and boilerplate while keeping essential words strictly verbatim in their exact original order.\n"
    "RULES:\n"
    "1. Copy words strictly verbatim from the input in original order. NEVER paraphrase, rewrite, or add new words.\n"
    "2. Target keeping roughly 60% to 75% of the original words evenly across the passage.\n"
    "3. Always preserve ALL entities, names, dates, numbers, negations, technical terms, and JSON/code keys & values.\n"
    "4. Output ONLY the compressed text — no preamble, no explanations, no markdown fences."
)


def collect_held_out_hashes() -> set[str]:
    """Collect normalized hashes from all zero-touch eval suites so zero test docs ever enter train/val."""
    hashes: set[str] = set()
    specs = [
        ("rajpurkar/squad_v2", "squad_v2/validation-00000-of-00001.parquet", "context", 5000),
        ("hotpotqa/hotpot_qa", "distractor/validation-00000-of-00001.parquet", "question", 5000),
        ("openai/gsm8k", "main/test-00000-of-00001.parquet", "question", 2000),
    ]
    for repo, fn, col, lim in specs:
        try:
            for r in iter_parquet_rows(repo, fn, [col], limit=lim):
                t = str(r.get(col, "") or "")
                if t:
                    hashes.add(norm_hash(t))
        except Exception as e:
            print(f"[warn] held-out hash fetch {repo}: {e}", flush=True)
    return hashes


def load_existing_v1_docs() -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for split_fn in ("data/train-00000-of-00001.parquet", "data/validation-00000-of-00001.parquet"):
        try:
            local = hf_hub_download("Tamarillo/prompt-compression-corpus-2026", split_fn, repo_type="dataset")
            rows.extend(pq.read_table(local).to_pylist())
        except Exception as e:
            print(f"[warn] could not load existing {split_fn}: {e}", flush=True)
    print(f"[v2] Loaded {len(rows)} existing v1 rows from Tamarillo/prompt-compression-corpus-2026", flush=True)
    return rows


def collect_new_source_documents(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. FiscalNote/billsum (CC0-1.0) -> 1,200 new policy docs
    c = 0
    for r in iter_parquet_rows("FiscalNote/billsum", "data/train-00000-of-00001.parquet", ["text"], limit=10000):
        if c >= 1200: break
        if add_doc(r.get("text", ""), "billsum_policy", "FiscalNote/billsum", "cc0-1.0", "en", 200, 950):
            c += 1

    # 2. qiaojin/PubMedQA (MIT) -> 1,500 new scientific abstracts
    c = 0
    for r in iter_parquet_rows("qiaojin/PubMedQA", "pqa_artificial/train-00000-of-00001.parquet", ["context"], limit=12000):
        if c >= 1500: 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", 140, 750):
            c += 1

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

    # 4. HuggingFaceH4/ultrachat_200k (MIT) -> 1,200 technical/multi-turn passages
    c = 0
    try:
        for r in iter_parquet_rows("HuggingFaceH4/ultrachat_200k", "data/train_sft-00000-of-00003-a3ecf92756993583.parquet", ["messages"], limit=10000):
            if c >= 1200: 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", 140, 800):
                c += 1
    except Exception as e:
        print(f"[warn] ultrachat_200k skipped: {e}", flush=True)

    # 5. CohereLabs/aya_dataset (Apache-2.0) -> 1,500 multilingual passages (20+ languages!)
    c = 0
    for r in iter_parquet_rows("CohereLabs/aya_dataset", "data/train-00000-of-00001.parquet", ["inputs", "targets", "language"], limit=80000):
        if c >= 1500: 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, 80, 600):
            c += 1

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

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

    rng.shuffle(docs)
    return docs


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--teacher", type=str, default="Qwen/Qwen3-14B")
    parser.add_argument("--batch-size", type=int, default=96)
    parser.add_argument("--max-minutes", type=float, default=90.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(2027)

    existing_v1 = load_existing_v1_docs()
    blocked_hashes = collect_held_out_hashes()
    for r in existing_v1:
        blocked_hashes.add(norm_hash(r.get("text", "")))

    docs = collect_new_source_documents(blocked_hashes, rng)
    print(f"[v2] Collected {len(docs)} NEW 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):
        # Assign multi-rate target per doc (50% aggressive 40-55%, 50% gentle 60-75%) for calibrated ranking!
        sys_p = PROMPT_AGGRESSIVE if (doc_i % 2 == 0) else PROMPT_GENTLE
        chs = split_sentence_chunks(d["text"], max_words=220)
        for ch_i, ch in enumerate(chs):
            if len(WORD_RE.findall(ch)) >= 25:
                doc_to_chunks.setdefault(doc_i, []).append((ch_i, ch, sys_p))
                total_flat += 1
    print(f"[v2] Flattened -> {total_flat:,} new 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

    # Try vLLM for 8-10x speedup; fallback cleanly to BF16 SDPA HF generate!
    llm_vllm = None
    try:
        from vllm import LLM, SamplingParams
        print(f"[v2] Initializing vLLM engine for {args.teacher} (BF16)...", flush=True)
        llm_vllm = LLM(
            model=args.teacher,
            dtype="bfloat16",
            max_model_len=2048,
            gpu_memory_utilization=0.90,
            enforce_eager=False,
        )
        vllm_sp = SamplingParams(temperature=0.0, max_tokens=240)
        print("[v2] vLLM engine READY!", flush=True)
    except Exception as e:
        print(f"[v2] vLLM unavailable ({e}); using HF BF16 SDPA generate(bs={args.batch_size})", flush=True)
        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
    new_aligned: list[dict[str, Any]] = []
    total_chunks_done = 0
    total_chunks_passed = 0
    wave_size = 800
    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(new_aligned)} new 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)

        if llm_vllm is not None:
            outs = llm_vllm.generate(w_prompts, vllm_sp, use_tqdm=False)
            for idx, o in zip(w_order, outs):
                w_comp[idx] = o.outputs[0].text.strip() if o.outputs else ""
        else:
            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]
                max_w = max(len(WORD_RE.findall(w_items[k][2])) for k in idxs)
                max_new = min(240, max(64, int(max_w * 0.92)))
                with torch.no_grad():
                    gen = model.generate(**enc, max_new_tokens=max_new, do_sample=False, pad_token_id=tok.pad_token_id)
                for k, d_txt in zip(idxs, tok.batch_decode(gen[:, in_len:], skip_special_tokens=True)):
                    w_comp[k] = d_txt.strip()

        by_doc_res: dict[int, list[tuple[int, list[str], list[int], float, float]]] = {}
        for (di, ci, orig_ch, _sp), comp_ch in zip(w_items, w_comp):
            ow, cw = WORD_RE.findall(orig_ch), WORD_RE.findall(comp_ch)
            labels, fid = align_extractive_lcs(ow, cw)
            ret = sum(labels) / max(len(ow), 1)
            total_chunks_done += 1
            if fid >= 0.90 and 0.18 <= ret <= 0.88:
                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) < max(1, int(np.ceil(0.8 * orig_n))):
                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]
            new_aligned.append({
                "doc_id": f"tamarillo_pc_v2_{len(new_aligned):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)
        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}%) "
            f"new_docs={len(new_aligned):,} speed={cpm:.1f} ch/min elapsed={el / 60:.1f}m",
            flush=True,
        )

    synth_sec = time.perf_counter() - t0
    if llm_vllm is not None:
        del llm_vllm
    else:
        del model
    gc.collect()
    torch.cuda.empty_cache()

    # Merge existing v1 (1,550 docs) + new multi-rate v2 docs cleanly!
    all_docs = existing_v1 + new_aligned
    rng.shuffle(all_docs)
    n_val = max(300, int(0.05 * len(all_docs)))
    val_docs = all_docs[:n_val]
    tr_docs = all_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")

    summary = {
        "version": "v2_multirate",
        "teacher": args.teacher,
        "v1_docs_merged": len(existing_v1),
        "v2_new_docs": len(new_aligned),
        "total_docs_kept": len(all_docs),
        "train_docs": len(tr_docs),
        "val_docs": len(val_docs),
        "total_chunks_processed": total_chunks_done,
        "total_chunks_passed": total_chunks_passed,
        "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 all_docs])), 1) if all_docs else 0.0,
        "mean_retention": round(float(np.mean([d["retention_ratio"] for d in all_docs])), 4) if all_docs else 0.0,
        "mean_lcs_fidelity": round(float(np.mean([d["lcs_fidelity"] for d in all_docs])), 4) if all_docs else 0.0,
        "by_domain": dict(Counter(d["domain"] for d in all_docs)),
        "by_license": dict(Counter(d["source_license"] for d in all_docs)),
        "n_languages": len({d["lang"] for d in all_docs}),
    }
    (out_dir / "corpus_summary_v2.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print("\n=== PROMPT-COMPRESSION-CORPUS-2026 V2 SYNTHESIS COMPLETE ===")
    print(json.dumps(summary, indent=2), flush=True)


if __name__ == "__main__":
    main()