File size: 16,486 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
#!/usr/bin/env python3
"""
Self-Gating Truncation-Free, EOS-Verified, Flat-Decile Corpus Synthesizer (`v3`)
using Apache-2.0 `Qwen/Qwen3-8B` (BF16 SDPA, `bs=192`, 1-shot aggressive word-deletion prompt).

Phase A (~6 min):
  - Compresses all 590 zero-touch 5-suite eval docs (`HotpotQA`, `SQuAD-v2`, `GSM8K CoT`, `XQuAD`, `Agent JSON`),
    measures exact chunk pass rate, mean retention, 10-decile positional balance, AND runs frozen non-Qwen
    `microsoft/Phi-4-mini-instruct` Reader-QA!
  - Automatic Go Gate: proceeds to Phase B ONLY if `pass_rate >= 0.65`, `min(deciles) >= 0.25`,
    AND `mean_5suite_score >= 0.56` (matching/beating `llmlingua-2-mBERT` `0.5597` @ 0.50x)!

Phase B (~38 min, same VM):
  - Synthesizes ~4,500-6,500 spotless, EOS-verified, flat-decile pure Apache-2.0 / MIT / CC0-1.0 docs
    across 7 domains & 40+ languages (`<=120w` chunks, `max_new_tokens=240`, strict EOS check, zero truncation).
"""
from __future__ import annotations

import argparse
import gc
import json
import random
import re
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 eval_pc_5suite import build_5_suites, eval_with_reader
from synth_corpus_2026 import WORD_RE, align_extractive_lcs, split_sentence_chunks
from synth_corpus_v2 import collect_held_out_hashes
from synth_corpus_v3_clean import collect_fresh_docs, compute_decile_curve

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

LLMLINGUA2_SYS_PROMPT = (
    "Compress the given text into a much shorter sequence of words so that an LLM can still reconstruct "
    "the original meaning and answer any factual, numerical, or JSON question accurately. Comply with all 5 rules:\n"
    "1. You can ONLY remove unimportant words (articles, filler, redundancy).\n"
    "2. Do NOT reorder the original words.\n"
    "3. Do NOT change, paraphrase, or abbreviate the original words.\n"
    "4. Do NOT add new words, labels, or explanations.\n"
    "5. Compress aggressively across the ENTIRE passage from start to the very last word (~45-55% of original words kept), "
    "always keeping key nouns, entities, numbers, operators, negations, verbs, and JSON keys/values."
)

FEWSHOT_USER = (
    "During the third quarter of 2025, the enterprise billing API service in us-east-1 experienced "
    "a temporary spike in latency that reached 420 milliseconds due to a database connection pool exhaustion, "
    "and the on-call engineering team resolved the incident within 18 minutes by increasing the pool limit from 50 to 120."
)
FEWSHOT_ASST = (
    "third quarter 2025 enterprise billing API us-east-1 spike latency 420 milliseconds database connection pool exhaustion "
    "on-call engineering resolved 18 minutes increasing pool limit 50 120."
)


def align_fuzzy_lcs(orig_words: list[str], comp_words: list[str]) -> tuple[list[int], float]:
    """Exact DP-LCS first, with light alphanumeric-stem normalization so minor punctuation edits align cleanly."""
    labels, fid = align_extractive_lcs(orig_words, comp_words)
    if fid >= 0.88:
        return labels, fid
    # Fuzzy stem fallback (strip punctuation + 5-char stem)
    def stem(w: str) -> str:
        s = re.sub(r"[^\w]", "", w.lower())
        return s[:6] if len(s) > 6 else (s or w.lower())

    n, m = len(orig_words), len(comp_words)
    if n == 0 or m == 0:
        return [0] * n, 0.0
    on = [stem(w) for w in orig_words]
    cn = [stem(w) for w in comp_words]
    dp = np.zeros((n + 1, m + 1), dtype=np.int32)
    for i in range(1, n + 1):
        ow = on[i - 1]
        prev, curr = dp[i - 1], dp[i]
        for j in range(1, m + 1):
            if ow == cn[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, matched = n, m, 0
    while i > 0 and j > 0:
        if on[i - 1] == cn[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 run_batch_compress(
    model: torch.nn.Module,
    tok: Any,
    chunks: list[str],
    batch_size: int,
    max_new: int = 240,
) -> tuple[list[str], list[bool]]:
    eos_ids = {tok.eos_token_id}
    if tok.pad_token_id is not None:
        eos_ids.add(tok.pad_token_id)

    order = sorted(range(len(chunks)), key=lambda i: len(chunks[i]))
    prompts = []
    for i in order:
        msgs = [
            {"role": "system", "content": LLMLINGUA2_SYS_PROMPT},
            {"role": "user", "content": FEWSHOT_USER},
            {"role": "assistant", "content": FEWSHOT_ASST},
            {"role": "user", "content": chunks[i]},
        ]
        try:
            p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
        except TypeError:
            p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
        prompts.append(p)

    comp = [""] * len(chunks)
    hit_cap = [False] * len(chunks)
    for st in range(0, len(order), batch_size):
        idxs = order[st : st + batch_size]
        enc = tok(prompts[st : st + batch_size], padding=True, truncation=True, max_length=768, return_tensors="pt").to("cuda")
        in_l = enc["input_ids"].shape[1]
        with torch.inference_mode():
            gen = model.generate(**enc, max_new_tokens=max_new, do_sample=False, pad_token_id=tok.pad_token_id)
        gn = gen[:, in_l:]
        decs = tok.batch_decode(gn, skip_special_tokens=True)
        for rj, (orig_i, txt) in enumerate(zip(idxs, decs)):
            last_t = int(gn[rj, -1].item())
            hit_cap[orig_i] = (gn.shape[1] >= max_new) and (last_t not in eos_ids)
            comp[orig_i] = txt.strip()
    return comp, hit_cap


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

    print(f"[v3-gate] Loading teacher {args.teacher} (BF16 SDPA)...", 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, attn_implementation="sdpa").to("cuda").eval()

    # ==================== PHASE A: 5-SUITE ZERO-TOUCH TEACHER GATE ====================
    print("\n=== [PHASE A] Testing 1-Shot Aggressive Teacher on All 5 Zero-Touch Suites ===", flush=True)
    t_a = time.perf_counter()
    qa_rows = build_5_suites()
    flat_qa: list[tuple[int, str]] = []
    for di, r in enumerate(qa_rows):
        for ch in split_sentence_chunks(r["context"], max_words=120):
            flat_qa.append((di, ch))
    qa_comp, qa_cap = run_batch_compress(model, tok, [x[1] for x in flat_qa], batch_size=args.batch_size, max_new=240)
    a_sec = time.perf_counter() - t_a
    print(f"[PHASE A] Compressed {len(flat_qa)} QA chunks in {a_sec:.1f}s ({len(flat_qa)/(a_sec/60):.1f} ch/min)", flush=True)

    by_doc_txt: dict[int, list[str]] = {i: [] for i in range(len(qa_rows))}
    by_doc_lbl: dict[int, list[int]] = {i: [] for i in range(len(qa_rows))}
    pass_c, trunc_c, rets, fids = 0, 0, [], []
    for (di, orig_ch), comp_ch, cap in zip(flat_qa, qa_comp, qa_cap):
        ow, cw = WORD_RE.findall(orig_ch), WORD_RE.findall(comp_ch)
        labels, fid = align_fuzzy_lcs(ow, cw)
        ret = sum(labels) / max(len(ow), 1)
        if cap:
            trunc_c += 1
        if (not cap) and fid >= 0.85 and 0.20 <= ret <= 0.82:
            pass_c += 1
        rets.append(ret); fids.append(fid)
        kept = [w for w, lb in zip(ow, labels) if lb == 1]
        if len(kept) < max(4, int(0.15 * len(ow))):
            kept = ow
        by_doc_txt[di].append(" ".join(kept))
        by_doc_lbl[di].extend(labels)

    qa_deciles = compute_decile_curve([{"labels": by_doc_lbl[i]} for i in range(len(qa_rows))])
    pass_rate_a = pass_c / max(len(flat_qa), 1)
    mean_ret_a = float(np.mean(rets))
    mean_fid_a = float(np.mean(fids))
    print(f"[PHASE A STATS] pass_rate={pass_rate_a:.3f} trunc={trunc_c}/{len(flat_qa)} mean_ret={mean_ret_a:.3f} mean_fid={mean_fid_a:.3f} deciles={qa_deciles}", flush=True)

    # Temporarily offload teacher to CPU while Phi-4-mini-instruct runs Reader-QA (~3 min)
    model.cpu(); torch.cuda.empty_cache()
    teacher_ctxs = ["\n\n".join(by_doc_txt[i]) for i in range(len(qa_rows))]
    qa_eval = eval_with_reader(qa_rows, {"qwen3_8b_1shot_teacher": teacher_ctxs}, args.reader)
    s5 = qa_eval["qwen3_8b_1shot_teacher"]["mean_5suite_score"]
    s4 = qa_eval["qwen3_8b_1shot_teacher"]["mean_4en_score"]
    gate_report = {
        "teacher": args.teacher,
        "reader": args.reader,
        "qa_chunks": len(flat_qa),
        "qa_chunks_per_min": round(len(flat_qa) / max(a_sec / 60.0, 1e-6), 1),
        "pass_rate": round(pass_rate_a, 4),
        "eos_trunc_count": trunc_c,
        "mean_retention": round(mean_ret_a, 4),
        "mean_fidelity": round(mean_fid_a, 4),
        "deciles_0_to_9": qa_deciles,
        "reader_qa": qa_eval["qwen3_8b_1shot_teacher"],
    }
    gate_passed = (pass_rate_a >= 0.65) and (min(qa_deciles) >= 0.25) and (s5 >= 0.56)
    gate_report["gate_passed"] = gate_passed
    (out_dir / "phase_a_gate.json").write_text(json.dumps(gate_report, indent=2), encoding="utf-8")
    print(f"[PHASE A GATE] s5={s5:.4f} s4={s4:.4f} pass_rate={pass_rate_a:.3f} min_decile={min(qa_deciles):.3f} -> GATE={'PASS' if gate_passed else 'STOP'}", flush=True)

    if not gate_passed:
        print("[PHASE A] Gate did NOT pass — stopping early to save compute!", flush=True)
        return

    # ==================== PHASE B: SCALE TO 4,500-6,500 SPOTLESS DOCS ====================
    print("\n=== [PHASE B] Gate PASSED! Scaling Truncation-Free Flat-Decile Corpus v3 ===", flush=True)
    model.to("cuda").eval()
    blocked = collect_held_out_hashes()
    docs = collect_fresh_docs(blocked, rng)
    doc_to_chunks: dict[int, list[tuple[int, str]]] = {}
    for di, d in enumerate(docs):
        for ci, ch in enumerate(split_sentence_chunks(d["text"], max_words=120)):
            if len(WORD_RE.findall(ch)) >= 20:
                doc_to_chunks.setdefault(di, []).append((ci, ch))

    t0 = time.perf_counter()
    deadline = t0 + args.max_minutes * 60.0
    aligned_docs: list[dict[str, Any]] = []
    tot_ch, tot_pass, tot_trunc, tot_pos = 0, 0, 0, 0
    doc_ids = list(doc_to_chunks.keys())
    wave_size = 750

    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 with {len(aligned_docs):,} spotless docs.", flush=True)
            break
        w_dids = doc_ids[w_start : w_start + wave_size]
        w_items = [(di, ci, ch) for di in w_dids for (ci, ch) in doc_to_chunks[di]]
        w_comp, w_cap = run_batch_compress(model, tok, [x[2] for x in w_items], batch_size=args.batch_size, max_new=240)

        by_doc_res: dict[int, list[tuple[int, list[str], list[int], float, float]]] = {}
        for (di, ci, orig_ch), comp_ch, cap in zip(w_items, w_comp, w_cap):
            tot_ch += 1
            if cap:
                tot_trunc += 1
                continue
            ow, cw = WORD_RE.findall(orig_ch), WORD_RE.findall(comp_ch)
            labels, fid = align_fuzzy_lcs(ow, cw)
            n = len(ow)
            ret = sum(labels) / max(n, 1)
            if not (fid >= 0.85 and 0.20 <= ret <= 0.84):
                continue
            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.38:
                tot_pos += 1
                continue
            tot_pass += 1
            by_doc_res.setdefault(di, []).append((ci, ow, labels, fid, ret))

        for di in w_dids:
            orig_n = len(doc_to_chunks[di])
            res_list = sorted(by_doc_res.get(di, []), key=lambda x: x[0])
            # Require ALL chunks for <=2-chunk docs, or >=80% AND including the LAST chunk (so zero missing tails!)
            if not res_list:
                continue
            has_last = (res_list[-1][0] == orig_n - 1)
            if len(res_list) < max(1, int(np.ceil(0.80 * orig_n))) or not has_last:
                continue
            all_w, all_lb = [], []
            for _, ow, lb, _, _ in res_list:
                all_w.extend(ow); all_lb.extend(lb)
            dmeta = docs[di]
            aligned_docs.append({
                "doc_id": f"tamarillo_pc_v3_{len(aligned_docs):06d}",
                "text": " ".join(all_w),
                "compressed_text": " ".join(w for w, lb in zip(all_w, all_lb) if lb == 1),
                "words": all_w,
                "labels": all_lb,
                "n_words": len(all_w),
                "n_kept": int(sum(all_lb)),
                "retention_ratio": round(sum(all_lb) / max(len(all_w), 1), 4),
                "lcs_fidelity": round(float(np.mean([x[3] for x in res_list])), 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
        dec = compute_decile_curve(aligned_docs)
        print(
            f"  [Wave {w_start + len(w_dids):4d}/{len(doc_ids)}] ch={tot_ch:,} (pass={tot_pass/max(tot_ch,1)*100:.1f}%, trunc={tot_trunc}, pos={tot_pos}) "
            f"docs={len(aligned_docs):,} speed={tot_ch/max(el/60,1e-6):.1f} ch/m dec={dec}",
            flush=True,
        )

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

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

    summary = {
        "version": "v3_eos_verified_flat_decile_1shot",
        "teacher": args.teacher,
        "reader": args.reader,
        "phase_a_gate": gate_report,
        "total_docs_kept": len(aligned_docs),
        "train_docs": len(tr_docs),
        "val_docs": len(val_docs),
        "total_chunks_processed": tot_ch,
        "total_chunks_passed": tot_pass,
        "chunk_pass_rate": round(tot_pass / max(tot_ch, 1), 4),
        "eos_trunc_rejected": tot_trunc,
        "pos_imbalanced_rejected": tot_pos,
        "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": compute_decile_curve(aligned_docs),
        "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=== SELF-GATED CORPUS V3 COMPLETE ===")
    print(json.dumps(summary, indent=2), flush=True)


if __name__ == "__main__":
    main()