File size: 29,848 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#!/usr/bin/env python3
"""
Phase 1A-Full: Synthesize Pure Apache-2.0 / MIT / CC0-1.0 Extractive Prompt-Compression Dataset
(`Tamarillo/prompt-compression-corpus-2026`) using Apache-2.0 `Qwen/Qwen3-14B` (BF16, enable_thinking=False)
with sentence-boundary chunking (<=220 words/chunk) + exact DP-LCS extractive alignment +
end-to-end Reader-QA quality proof on frozen non-Qwen `microsoft/Phi-4-mini-instruct`.

100% Commercially Permissive Sources (ZERO ODC-BY, ZERO CC-BY-NC, ZERO CC-BY-SA, ZERO GPT-3.5 synthetic):
  - FiscalNote/billsum (CC0-1.0)
  - qiaojin/PubMedQA (MIT)
  - OpenAssistant/oasst2 (Apache-2.0)
  - CohereLabs/aya_dataset (Apache-2.0)
  - abisee/cnn_dailymail (Apache-2.0)
  - Programmatic structured Agent JSON / Observability Logs (Apache-2.0)
"""
from __future__ import annotations

import argparse
import gc
import hashlib
import json
import os
import random
import re
import string
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, AutoModelForTokenClassification, AutoTokenizer

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",
    }

SYSTEM_PROMPT = (
    "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 that a downstream AI assistant can still "
    "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 45% to 60% of the original words evenly across the entire 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."
)

WORD_RE = re.compile(r"\S+")
SENT_SPLIT_RE = re.compile(r"(?<=[.!?。!?])\s+")


def norm_hash(t: str) -> str:
    return hashlib.sha256(" ".join(t.lower().split())[:500].encode("utf-8", errors="ignore")).hexdigest()[:20]


def iter_parquet_rows(repo_id: str, filename: str, columns: list[str] | None = None, limit: int = 50000):
    local = hf_hub_download(repo_id=repo_id, filename=filename, repo_type="dataset")
    pf = pq.ParquetFile(local)
    yielded = 0
    for batch in pf.iter_batches(batch_size=512, columns=columns):
        for row in batch.to_pylist():
            yield row
            yielded += 1
            if yielded >= limit:
                return


def split_sentence_chunks(text: str, max_words: int = 220) -> list[str]:
    """Split text cleanly at paragraph & sentence boundaries keeping chunks <= max_words."""
    chunks: list[str] = []
    for para in re.split(r"\n\s*\n", text.strip()):
        para = para.strip()
        if not para:
            continue
        p_words = WORD_RE.findall(para)
        if len(p_words) <= max_words:
            chunks.append(" ".join(p_words))
            continue
        sents = SENT_SPLIT_RE.split(para)
        buf: list[str] = []
        for s in sents:
            sw = WORD_RE.findall(s)
            if not sw:
                continue
            if len(sw) > max_words:
                if buf:
                    chunks.append(" ".join(buf))
                    buf = []
                for st in range(0, len(sw), max_words):
                    chunks.append(" ".join(sw[st : st + max_words]))
            elif len(buf) + len(sw) > max_words:
                if buf:
                    chunks.append(" ".join(buf))
                buf = sw
            else:
                buf.extend(sw)
        if buf:
            chunks.append(" ".join(buf))
    return chunks


def norm_word(w: str) -> str:
    return re.sub(r"^[^\w]+|[^\w]+$", "", w.lower())


def align_extractive_lcs(orig_words: list[str], comp_words: list[str]) -> tuple[list[int], float]:
    n, m = len(orig_words), len(comp_words)
    if n == 0 or m == 0:
        return [0] * n, 0.0
    orig_norm = [norm_word(w) or w.lower() for w in orig_words]
    comp_norm = [norm_word(w) or w.lower() for w in comp_words]
    dp = np.zeros((n + 1, m + 1), dtype=np.int32)
    for i in range(1, n + 1):
        ow = orig_norm[i - 1]
        prev = dp[i - 1]
        curr = dp[i]
        for j in range(1, m + 1):
            if ow == comp_norm[j - 1]:
                curr[j] = prev[j - 1] + 1
            else:
                curr[j] = prev[j] if prev[j] >= curr[j - 1] else curr[j - 1]
    keep = [0] * n
    i, j = n, m
    matched = 0
    while i > 0 and j > 0:
        if orig_norm[i - 1] == comp_norm[j - 1]:
            keep[i - 1] = 1
            matched += 1
            i -= 1
            j -= 1
        elif dp[i - 1, j] >= dp[i, j - 1]:
            i -= 1
        else:
            j -= 1
    return keep, matched / m


def build_programmatic_logs(n: int, rng: random.Random) -> list[dict[str, Any]]:
    services = [
        "billing-api", "auth-gateway", "rag-retriever", "vector-indexer", "order-worker",
        "tool-router", "policy-engine", "embedding-proxy", "webhook-dispatcher", "ledger-sync",
    ]
    regions = ["us-central1", "us-east4", "eu-west1", "eu-central1", "ap-northeast1", "ap-southeast1"]
    errs = [
        "E_TIMEOUT_504", "E_POOL_EXHAUSTED", "E_SCHEMA_MISMATCH", "E_RATE_LIMIT_429",
        "E_TLS_HANDSHAKE", "E_DEADLOCK_40P01", "E_JWT_EXPIRED", "E_UPSTREAM_502",
    ]
    actions = [
        "inspect connection pool and replay failed webhook",
        "rotate expired signing key and verify JWKS cache",
        "increase statement_timeout and re-index partition",
        "enable exponential backoff and alert on-call SRE",
        "validate JSON payload schema against v2.4 contract",
    ]
    intros = [
        "Automated observability digest generated by monitoring daemon v4.2.1 for routine archival compliance across regional clusters.",
        "Periodic telemetry export emitted by infrastructure collector agent; standard UTC headers and verbose metadata follow below.",
        "Internal agent tool-execution audit envelope recorded during automated workflow triage with full diagnostic headers attached.",
    ]
    outros = [
        "Standby replicas reported nominal disk throughput, normal memory utilization, and healthy heartbeat responses prior to the incident.",
        "Routine background compaction jobs and scheduled certificate checks completed within expected SLA bounds during the same window.",
        "No unauthorized ingress changes or firewall rule modifications were observed by the perimeter watchdog daemon during this interval.",
    ]
    rows = []
    for _ in range(n):
        n_events = rng.choice([1, 2, 2, 3])
        parts = [rng.choice(intros)]
        for _ev in range(n_events):
            ev = {
                "request_id": f"req_{rng.randint(100000, 999999)}",
                "service": rng.choice(services),
                "region": rng.choice(regions),
                "account_id": f"acct_{rng.randint(1000, 9999)}",
                "status": rng.choice(["error", "degraded", "timeout"]),
                "error_code": rng.choice(errs),
                "latency_ms": rng.randint(45, 9500),
                "retries": rng.randint(1, 6),
                "action_required": rng.choice(actions),
            }
            parts.append(json.dumps(ev))
        parts.append(rng.choice(outros))
        rows.append({
            "text": "\n\n".join(parts),
            "domain": "agent_json_log",
            "source_dataset": "Tamarillo/programmatic-agent-logs",
            "source_license": "apache-2.0",
            "lang": "en",
        })
    return rows


def collect_source_documents(held_out_hashes: set[str], rng: random.Random) -> list[dict[str, Any]]:
    """Collect ~5,600 spotless multi-domain documents -> ~13,000-15,000 sentence-boundary chunks."""
    seen: set[str] = set()
    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 or h in held_out_hashes:
            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,000 long policy/legislative docs (300-1,100 words!)
    c = 0
    for r in iter_parquet_rows("FiscalNote/billsum", "data/train-00000-of-00001.parquet", ["text"], limit=4000):
        if c >= 1000: break
        if add_doc(r.get("text", ""), "billsum_policy", "FiscalNote/billsum", "cc0-1.0", "en", 250, 1100):
            c += 1

    # 2. qiaojin/PubMedQA (MIT) -> 1,300 dense scientific/technical abstracts
    c = 0
    for r in iter_parquet_rows("qiaojin/PubMedQA", "pqa_artificial/train-00000-of-00001.parquet", ["context"], limit=5000):
        if c >= 1300: 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", 150, 800):
            c += 1

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

    # 4. CohereLabs/aya_dataset (Apache-2.0) -> 1,200 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=40000):
        if c >= 1200: 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, 90, 650):
            c += 1

    # 5. abisee/cnn_dailymail (Apache-2.0) -> 600 long-form articles
    c = 0
    for r in iter_parquet_rows("abisee/cnn_dailymail", "3.0.0/train-00000-of-00003.parquet", ["article"], limit=3000):
        if c >= 600: break
        if add_doc(r.get("article", ""), "cnn_dm_news", "abisee/cnn_dailymail", "apache-2.0", "en", 220, 900):
            c += 1

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

    rng.shuffle(docs)
    return docs


def sample_qa_eval(n_squad: int = 50, n_hotpot: int = 50) -> list[dict[str, Any]]:
    qa: list[dict[str, Any]] = []
    c = 0
    for r in iter_parquet_rows("rajpurkar/squad_v2", "squad_v2/validation-00000-of-00001.parquet", ["context", "question", "answers"], limit=2000):
        if c >= n_squad: break
        ans = (r.get("answers") or {}).get("text", [])
        if ans and len(WORD_RE.findall(r.get("context", ""))) >= 90:
            qa.append({"suite": "squad_v2", "context": r["context"], "question": r["question"], "answers": list(set(ans))})
            c += 1
    c = 0
    for r in iter_parquet_rows("hotpotqa/hotpot_qa", "distractor/validation-00000-of-00001.parquet", ["context", "question", "answer", "supporting_facts"], limit=1000):
        if c >= n_hotpot: break
        titles = r["context"]["title"]
        sents = r["context"]["sentences"]
        sup = set(r["supporting_facts"]["title"])
        chosen, dist_added = [], 0
        for ti, se in zip(titles, sents):
            p = f"{ti}: " + " ".join(se)
            if ti in sup:
                chosen.append(p)
            elif dist_added < 4:
                chosen.append(p)
                dist_added += 1
        ctx = "\n\n".join(chosen)
        if len(WORD_RE.findall(ctx)) >= 250 and r.get("answer"):
            qa.append({"suite": "hotpotqa_rag", "context": ctx, "question": r["question"], "answers": [r["answer"]]})
            c += 1
    return qa


def norm_ans(s: str) -> str:
    s = s.lower()
    s = "".join(ch for ch in s if ch not in set(string.punctuation))
    s = re.sub(r"\b(a|an|the)\b", " ", s)
    return " ".join(s.split())


def token_f1(pred: str, golds: list[str]) -> tuple[float, float]:
    pn = norm_ans(pred)
    best_em, best_f1 = 0.0, 0.0
    for g in golds:
        gn = norm_ans(g)
        if pn == gn: best_em = 1.0
        pt, gt = pn.split(), gn.split()
        if not pt or not gt:
            f1 = 1.0 if pt == gt else 0.0
        else:
            common = sum((Counter(pt) & Counter(gt)).values())
            f1 = 0.0 if common == 0 else (2 * (common / len(pt)) * (common / len(gt)) / ((common / len(pt)) + (common / len(gt))))
        best_f1 = max(best_f1, f1)
    return best_em, best_f1


def compress_with_llmlingua2_model(repo_id: str, contexts: list[str], target_rates: list[float], device: str) -> list[str]:
    tok = AutoTokenizer.from_pretrained(repo_id, use_fast=True)
    mod = AutoModelForTokenClassification.from_pretrained(repo_id, torch_dtype=torch.bfloat16).to(device).eval()
    compressed = []
    for ctx, rate in zip(contexts, target_rates):
        words = [(m.start(), m.end(), m.group(0)) for m in WORD_RE.finditer(ctx)]
        if not words:
            compressed.append("")
            continue
        word_probs = []
        for st in range(0, len(words), 320):
            sub_txt = " ".join(w[2] for w in words[st : st + 320])
            enc = tok(sub_txt, return_offsets_mapping=True, truncation=True, max_length=512, return_tensors="pt")
            offsets = enc.pop("offset_mapping")[0].tolist()
            tin = {k: v.to(device) for k, v in enc.items() if k in ("input_ids", "attention_mask")}
            with torch.no_grad():
                logits = mod(**tin).logits[0].float().cpu().numpy()
            ex = np.exp(logits - logits.max(axis=-1, keepdims=True))
            pk = (ex / ex.sum(axis=-1, keepdims=True))[:, 1]
            sub_spans = [(m.start(), m.end()) for m in WORD_RE.finditer(sub_txt)]
            ti, nt = 0, len(offsets)
            for ws, we in sub_spans:
                sc = []
                while ti < nt and offsets[ti][1] <= ws: ti += 1
                j = ti
                while j < nt and offsets[j][0] < we:
                    if offsets[j][1] > offsets[j][0]: sc.append(float(pk[j]))
                    j += 1
                word_probs.append(float(np.mean(sc)) if sc else 0.5)
        n = len(words)
        word_probs = (word_probs + [0.5] * n)[:n]
        k = max(1, min(n, int(round(n * rate))))
        thr = sorted(word_probs, reverse=True)[k - 1]
        kept = [w[2] for w, p in zip(words, word_probs) if p >= thr]
        compressed.append(" ".join(kept[:k]))
    del mod; gc.collect(); torch.cuda.empty_cache()
    return compressed


def eval_reader(qa_rows: list[dict[str, Any]], contexts_by_sys: dict[str, list[str]], reader_id: str) -> dict[str, Any]:
    tok = AutoTokenizer.from_pretrained(reader_id, padding_side="left")
    if tok.pad_token_id is None: tok.pad_token_id = tok.eos_token_id
    mod = AutoModelForCausalLM.from_pretrained(reader_id, torch_dtype=torch.bfloat16).to("cuda").eval()
    out = {}
    for sname, ctxs in contexts_by_sys.items():
        prompts = []
        for r, c in zip(qa_rows, ctxs):
            msgs = [
                {"role": "system", "content": "Answer the question using ONLY the provided context. Give the shortest exact answer (a few words only, no explanation)."},
                {"role": "user", "content": f"Context:\n{c}\n\nQuestion: {r['question']}\nShort exact answer:"},
            ]
            prompts.append(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))
        preds = []
        for i in range(0, len(prompts), 16):
            enc = tok(prompts[i : i + 16], padding=True, truncation=True, max_length=2048, return_tensors="pt").to("cuda")
            in_len = enc["input_ids"].shape[1]
            with torch.no_grad():
                gen = mod.generate(**enc, max_new_tokens=32, do_sample=False, pad_token_id=tok.pad_token_id)
            preds.extend([x.strip().splitlines()[0] if x.strip() else "" for x in tok.batch_decode(gen[:, in_len:], skip_special_tokens=True)])
        by_suite, all_em, all_f1, all_ret = {}, [], [], []
        for r, c, p in zip(qa_rows, ctxs, preds):
            em, f1 = token_f1(p, r["answers"])
            ret = len(WORD_RE.findall(c)) / max(len(WORD_RE.findall(r["context"])), 1)
            all_em.append(em); all_f1.append(f1); all_ret.append(ret)
            by_suite.setdefault(r["suite"], []).append((em, f1, ret))
        out[sname] = {
            "mean_em": round(float(np.mean(all_em)), 4),
            "mean_f1": round(float(np.mean(all_f1)), 4),
            "mean_word_retention": round(float(np.mean(all_ret)), 4),
            "by_suite": {k: {"n": len(v), "em": round(float(np.mean([x[0] for x in v])), 4), "f1": round(float(np.mean([x[1] for x in v])), 4), "retention": round(float(np.mean([x[2] for x in v])), 4)} for k, v in by_suite.items()},
        }
        print(f"  [Reader {sname:26s}] F1={out[sname]['mean_f1']:.4f} EM={out[sname]['mean_em']:.4f} ret={out[sname]['mean_word_retention']:.3f}", flush=True)
    del mod; gc.collect(); torch.cuda.empty_cache()
    return out


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--teacher", type=str, default="Qwen/Qwen3-14B")
    parser.add_argument("--reader", type=str, default="microsoft/Phi-4-mini-instruct")
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--max-minutes", type=float, default=65.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(2026)

    print("[synth] Loading 100 zero-touch QA verification docs first (to freeze held-out hashes)...", flush=True)
    qa_rows = sample_qa_eval(50, 50)
    held_out_hashes = {norm_hash(r["context"]) for r in qa_rows}

    print("[synth] Collecting spotless pure Apache-2.0 / MIT / CC0-1.0 source docs...", flush=True)
    docs = collect_source_documents(held_out_hashes, rng)
    print(f"[synth] Collected {len(docs)} documents: {dict(Counter(d['domain'] for d in docs))}", flush=True)

    # Flatten into sentence-boundary chunks (<=220 words)
    flat_corpus: list[tuple[int, int, str]] = []
    for doc_i, d in enumerate(docs):
        chs = split_sentence_chunks(d["text"], max_words=220)
        for ch_i, ch in enumerate(chs):
            if len(WORD_RE.findall(ch)) >= 25:
                flat_corpus.append((doc_i, ch_i, ch))

    flat_qa: list[tuple[int, str]] = []
    for doc_i, r in enumerate(qa_rows):
        for ch in split_sentence_chunks(r["context"], max_words=220):
            flat_qa.append((doc_i, ch))
    print(f"[synth] Flattened -> {len(flat_corpus)} corpus chunks + {len(flat_qa)} QA verification chunks", flush=True)

    print(f"[synth] Loading Apache-2.0 teacher {args.teacher} (BF16)...", 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
    model = AutoModelForCausalLM.from_pretrained(args.teacher, torch_dtype=torch.bfloat16).to("cuda").eval()

    def build_prompt(txt: str) -> str:
        msgs = [{"role": "system", "content": SYSTEM_PROMPT}, {"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)

    # 1. Run QA verification chunks FIRST (~1 min) so teacher proof is guaranteed!
    print("[synth] Step 1: Compressing 100 zero-touch QA verification docs...", flush=True)
    qa_order = sorted(range(len(flat_qa)), key=lambda i: len(flat_qa[i][1]))
    qa_prompts = [build_prompt(flat_qa[i][1]) for i in qa_order]
    comp_qa = [""] * len(flat_qa)
    t_qa = time.perf_counter()
    for i in range(0, len(qa_order), args.batch_size):
        idxs = qa_order[i : i + args.batch_size]
        enc = tok(qa_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(flat_qa[k][1])) for k in idxs)
        max_new = min(220, max(64, int(max_w * 0.90)))
        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)):
            comp_qa[k] = d_txt.strip()
    print(f"  QA chunks done in {time.perf_counter() - t_qa:.1f}s", flush=True)

    # 2. Run main corpus chunks (sorted by doc_id? No, process in randomized doc groups sorted by chunk len inside waves
    #    so if time-cap hits we have balanced multi-domain complete documents!)
    print(f"[synth] Step 2: Compressing corpus chunks (time budget = {args.max_minutes:.0f} min)...", flush=True)
    t0 = time.perf_counter()
    deadline = t0 + args.max_minutes * 60.0

    # Group chunks by doc_i in waves of 500 docs so every domain is evenly represented even if capped
    doc_to_chunks: dict[int, list[tuple[int, str]]] = {}
    for doc_i, ch_i, ch in flat_corpus:
        doc_to_chunks.setdefault(doc_i, []).append((ch_i, ch))

    aligned_docs: list[dict[str, Any]] = []
    total_chunks_done = 0
    total_chunks_passed = 0
    wave_size = 500
    doc_ids = list(range(len(docs)))

    for w_start in range(0, len(doc_ids), wave_size):
        if time.perf_counter() >= deadline:
            print(f"  [TIME CAP] Reached {args.max_minutes} min after {len(aligned_docs)} docs ({total_chunks_done} chunks). Stopping cleanly.", flush=True)
            break
        w_doc_ids = doc_ids[w_start : w_start + wave_size]
        w_items = [(di, ci, ch) for di in w_doc_ids for (ci, ch) in doc_to_chunks.get(di, [])]
        w_order = sorted(range(len(w_items)), key=lambda idx: len(w_items[idx][2]))
        w_prompts = [build_prompt(w_items[idx][2]) for idx in w_order]
        w_comp = [""] * 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]
            max_w = max(len(WORD_RE.findall(w_items[k][2])) for k in idxs)
            max_new = min(220, max(64, int(max_w * 0.90)))
            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()

        # Reassemble per document in this wave, keeping only high-fidelity aligned documents!
        by_doc_res: dict[int, list[tuple[int, list[str], list[int], float, float]]] = {}
        for (di, ci, orig_ch), 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.80:
                total_chunks_passed += 1
                by_doc_res.setdefault(di, []).append((ci, ow, labels, fid, ret))

        for di in w_doc_ids:
            orig_n_chunks = len(doc_to_chunks.get(di, []))
            res_list = sorted(by_doc_res.get(di, []), key=lambda x: x[0])
            # Keep document if ALL chunks (or >=80% for 5+ chunk docs) passed strict >=0.90 DP-LCS fidelity!
            if not res_list or len(res_list) < max(1, int(np.ceil(0.8 * orig_n_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)
            comp_txt = " ".join(w for w, lb in zip(all_words, all_labels) if lb == 1)
            dmeta = docs[di]
            aligned_docs.append({
                "doc_id": f"tamarillo_pc_{len(aligned_docs):06d}",
                "text": " ".join(all_words),
                "compressed_text": comp_txt,
                "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(docs)}] chunks={total_chunks_done} (pass={total_chunks_passed/max(total_chunks_done,1)*100:.1f}%) docs_kept={len(aligned_docs)} speed={cpm:.1f} ch/min elapsed={el/60:.1f}m", flush=True)

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

    # Save clean Parquet (train/validation 95/5 split) immediately!
    rng.shuffle(aligned_docs)
    n_val = max(200, 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")
    print(f"[synth] Saved Parquet: train={len(tr_docs)}, validation={len(val_docs)}", flush=True)

    # 3. Run Reader-QA verification on frozen non-Qwen Phi-4-mini-instruct vs BOTH LLMLingua-2 incumbents!
    by_qa: dict[int, list[str]] = {i: [] for i in range(len(qa_rows))}
    for (doc_i, orig_ch), comp_ch in zip(flat_qa, comp_qa):
        ow, cw = WORD_RE.findall(orig_ch), WORD_RE.findall(comp_ch)
        labels, _ = align_extractive_lcs(ow, cw)
        kept = [w for w, lb in zip(ow, labels) if lb == 1]
        if len(kept) < max(5, int(0.15 * len(ow))): kept = ow
        by_qa[doc_i].append(" ".join(kept))

    teacher_ctxs = ["\n\n".join(by_qa[i]) for i in range(len(qa_rows))]
    orig_ctxs = [r["context"] for r in qa_rows]
    matched_rates = [len(WORD_RE.findall(tc)) / max(len(WORD_RE.findall(oc)), 1) for tc, oc in zip(teacher_ctxs, orig_ctxs)]

    mbert_ctxs = compress_with_llmlingua2_model("microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank", orig_ctxs, matched_rates, "cuda")
    xlmr_ctxs = compress_with_llmlingua2_model("microsoft/llmlingua-2-xlm-roberta-large-meetingbank", orig_ctxs, matched_rates, "cuda")

    reader_res = eval_reader(
        qa_rows,
        {
            "uncompressed": orig_ctxs,
            "llmlingua2_mbert_178m": mbert_ctxs,
            "llmlingua2_xlmr_560m": xlmr_ctxs,
            "teacher_qwen3_14b_lcs": teacher_ctxs,
        },
        args.reader,
    )

    summary = {
        "teacher": args.teacher,
        "reader": args.reader,
        "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,
        "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,
        "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}),
        "reader_qa_verification": reader_res,
    }
    (out_dir / "corpus_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print("\n=== CORPUS SYNTHESIS & READER-QA VERIFICATION COMPLETE ===")
    print(json.dumps(summary, indent=2), flush=True)


if __name__ == "__main__":
    main()