File size: 17,060 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
#!/usr/bin/env python3
"""
5-Suite Zero-Touch Downstream Reader-QA Benchmark + Same-Machine 4-Thread CPU ONNX Latency
for `Tamarillo/prompt-compressor-{tiny-en,small}` vs. Uncompressed, `llmlingua-2-mBERT` (178M),
and `llmlingua-2-XLM-R-Large` (560M) using independent frozen non-Qwen `microsoft/Phi-4-mini-instruct`.

Suites (ZERO overlap with `Tamarillo/prompt-compression-corpus-2026`):
  1. `ood_hotpotqa_rag` (hotpotqa/hotpot_qa distractor val, n=120, multi-doc RAG)
  2. `ood_squad_v2` (rajpurkar/squad_v2 val, n=150, factual QA)
  3. `ood_gsm8k_math` (openai/gsm8k test, n=100, numeric & constraint preservation)
  4. `ood_multilingual_xquad` (google/xquad de/es/zh/ar/hi, 24 each = n=120)
  5. `ood_agent_json_qa` (deterministic held-out multi-service JSON tool-trace QA, n=100, different schema/seed)
"""
from __future__ import annotations

import argparse
import gc
import json
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 onnxruntime as ort
import torch
import transformers.modeling_utils as _tmu
from datasets import load_dataset
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForTokenClassification, AutoTokenizer

from synth_corpus_2026 import WORD_RE, iter_parquet_rows, token_f1

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

NUM_RE = re.compile(r"-?\d[\d,]*(?:\.\d+)?")


def _extract_last_num(s: str) -> str:
    ms = NUM_RE.findall(s or "")
    if not ms:
        return ""
    return ms[-1].replace(",", "").rstrip(".")


def build_5_suites() -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []

    # 1. ood_hotpotqa_rag (n=120)
    c = 0
    for r in iter_parquet_rows("hotpotqa/hotpot_qa", "distractor/validation-00000-of-00001.parquet", ["context", "question", "answer", "supporting_facts"], limit=2000):
        if c >= 120: 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 < 5:
                chosen.append(p)
                dist_added += 1
        ctx = "\n\n".join(chosen)
        if len(WORD_RE.findall(ctx)) >= 280 and r.get("answer"):
            rows.append({"suite": "ood_hotpotqa_rag", "context": ctx, "question": r["question"], "answers": [r["answer"]], "metric": "qa_f1"})
            c += 1

    # 2. ood_squad_v2 (n=150)
    c = 0
    for r in iter_parquet_rows("rajpurkar/squad_v2", "squad_v2/validation-00000-of-00001.parquet", ["context", "question", "answers"], limit=3000):
        if c >= 150: break
        ans = (r.get("answers") or {}).get("text", [])
        if ans and len(WORD_RE.findall(r.get("context", ""))) >= 90:
            rows.append({"suite": "ood_squad_v2", "context": r["context"], "question": r["question"], "answers": list(set(ans)), "metric": "qa_f1"})
            c += 1

    # 3. ood_gsm8k_math (n=100) — wrap each problem with realistic verbose system/context preamble so 0.50x tests preserving math facts!
    c = 0
    preambles = [
        "Background note from automated tutoring log: Please review the full word problem carefully, check all units and intermediate quantities, and compute the final numeric result without rounding errors.",
        "Session context recorded by workflow orchestrator: The student submitted the following quantitative scenario for step-by-step verification and exact numerical solution.",
    ]
    for r in iter_parquet_rows("openai/gsm8k", "main/test-00000-of-00001.parquet", ["question", "answer"], limit=500):
        if c >= 100: break
        ans_raw = str(r.get("answer", ""))
        gold = ans_raw.split("####")[-1].strip().replace(",", "") if "####" in ans_raw else _extract_last_num(ans_raw)
        if gold:
            ctx = f"{preambles[c % len(preambles)]}\n\nProblem details: {r['question']}\n\nNote: Ensure all stated rates, counts, and constraints from the problem details are respected."
            rows.append({"suite": "ood_gsm8k_math", "context": ctx, "question": "What is the exact final numerical answer to the problem?", "answers": [gold], "metric": "num_em"})
            c += 1

    # 4. ood_multilingual_xquad (de, es, zh, ar, hi — 24 each = 120)
    for lg in ("de", "es", "zh", "ar", "hi"):
        try:
            ds = load_dataset("google/xquad", f"xquad.{lg}", split="validation")
            c = 0
            for r in ds:
                if c >= 24: break
                ans = (r.get("answers") or {}).get("text", [])
                if ans and len(str(r.get("context", ""))) >= 200:
                    rows.append({"suite": "ood_multilingual_xquad", "lang": lg, "context": r["context"], "question": r["question"], "answers": list(set(ans)), "metric": "qa_f1"})
                    c += 1
        except Exception as e:
            print(f"[eval_pc] warn xquad.{lg}: {e}", flush=True)

    # 5. ood_agent_json_qa (n=100 — completely distinct e-commerce / K8s incident schema, zero overlap with train logs)
    rng = random.Random(99991)
    clusters = ["prod-k8s-us1", "prod-k8s-eu2", "staging-ap1", "edge-sa1", "core-us2"]
    pods = ["checkout-svc", "inventory-sync", "search-ranker", "fraud-scorer", "mail-relay"]
    codes = ["OOMKilled", "CrashLoopBackOff", "ImagePullBackOff", "ReadinessProbeFailed", "DeadlineExceeded"]
    for i in range(100):
        target_pod = rng.choice(pods)
        target_cluster = rng.choice(clusters)
        target_code = rng.choice(codes)
        target_mem = rng.randint(512, 8192)
        target_ticket = f"INC-{rng.randint(10000, 99999)}"
        recs = []
        for j in range(3):
            if j == (i % 3):
                recs.append({
                    "incident_id": target_ticket, "cluster": target_cluster, "pod": target_pod,
                    "reason": target_code, "memory_mb": target_mem, "severity": "critical",
                })
            else:
                recs.append({
                    "incident_id": f"INC-{rng.randint(10000, 99999)}", "cluster": rng.choice(clusters),
                    "pod": rng.choice([p for p in pods if p != target_pod]), "reason": "Healthy",
                    "memory_mb": rng.randint(128, 512), "severity": "info",
                })
        ctx = (
            "Kubernetes cluster telemetry dump archived by periodic observability cron job for standard compliance retention. "
            "All healthy baseline nodes passed liveness probes and scheduled log rotation completed without warnings. "
            + " ".join(json.dumps(x) for x in recs)
            + " Routine metrics scraping, Prometheus rule evaluation, and TLS certificate checks remained within SLA targets."
        )
        rows.append({
            "suite": "ood_agent_json_qa",
            "context": ctx,
            "question": f"What is the failure reason and incident_id for pod {target_pod}?",
            "answers": [f"{target_code} {target_ticket}", f"{target_ticket} {target_code}", target_code],
            "metric": "qa_f1",
        })

    print(f"[eval_pc] Built 5 zero-touch suites: {dict(Counter(r['suite'] for r in rows))}", flush=True)
    return rows


def compress_contexts(
    model_path: str,
    contexts: list[str],
    rate: float,
    max_chunk_words: int,
    max_seq_len: int,
    device: str = "cuda",
) -> list[str]:
    cfg = AutoConfig.from_pretrained(model_path)
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False
    tok = AutoTokenizer.from_pretrained(model_path, use_fast=True)
    kw = {"attn_implementation": "eager"} if getattr(cfg, "model_type", "") == "modernbert" else {}
    mod = AutoModelForTokenClassification.from_pretrained(model_path, config=cfg, torch_dtype=torch.bfloat16, **kw).to(device).eval()

    out = []
    for ctx in contexts:
        words = [(m.start(), m.end(), m.group(0)) for m in WORD_RE.finditer(ctx)]
        if not words:
            out.append("")
            continue
        word_probs = []
        for st in range(0, len(words), max_chunk_words):
            sub_txt = " ".join(w[2] for w in words[st : st + max_chunk_words])
            enc = tok(sub_txt, return_offsets_mapping=True, truncation=True, max_length=max_seq_len, return_token_type_ids=False, 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]
        out.append(" ".join(kept[:k]))
    del mod; gc.collect(); torch.cuda.empty_cache()
    return out


def bench_mbert_onnx_cpu(threads: int = 4) -> dict[str, Any]:
    """Export llmlingua-2-mBERT (178M, 512 cap) to temp FP32 ONNX for apples-to-apples same-machine CPU latency."""
    repo = "microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank"
    tok = AutoTokenizer.from_pretrained(repo, use_fast=True)
    mod = AutoModelForTokenClassification.from_pretrained(repo).eval().cpu()
    tmp_p = Path("/tmp/mbert_llmlingua2_fp32.onnx")
    enc = tok("Sample prompt compression benchmark text.", return_tensors="pt")
    with torch.no_grad():
        torch.onnx.export(
            mod, (enc["input_ids"], enc["attention_mask"]), str(tmp_p),
            input_names=["input_ids", "attention_mask"], output_names=["logits"],
            dynamic_axes={"input_ids": {0: "b", 1: "s"}, "attention_mask": {0: "b", 1: "s"}, "logits": {0: "b", 1: "s"}},
            opset_version=17,
        )
    opts = ort.SessionOptions()
    opts.intra_op_num_threads = threads
    opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
    sess = ort.InferenceSession(str(tmp_p), sess_options=opts, providers=["CPUExecutionProvider"])
    rep: dict[str, Any] = {"size_mb": round(tmp_p.stat().st_size / (1024 * 1024), 2)}
    for sl, n_chunks, runs in [(256, 1, 10), (512, 1, 8), (1024, 2, 4), (2048, 4, 4)]:
        c_len = min(512, sl)
        ids = np.full((1, c_len), 100, dtype=np.int64)
        mask = np.ones((1, c_len), dtype=np.int64)
        sess.run(["logits"], {"input_ids": ids, "attention_mask": mask})
        ts = []
        for _ in range(runs):
            t0 = time.perf_counter()
            for _ in range(n_chunks):
                sess.run(["logits"], {"input_ids": ids, "attention_mask": mask})
            ts.append((time.perf_counter() - t0) * 1000.0)
        rep[f"cpu_{sl}"] = {"seq_len": sl, "chunks_512": n_chunks, "p50_ms": round(float(np.median(ts)), 2)}
    tmp_p.unlink(missing_ok=True)
    del sess, mod
    return rep


def eval_with_reader(rows: list[dict[str, Any]], ctxs_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()

    results = {}
    for sname, ctxs in ctxs_by_sys.items():
        prompts = []
        is_math = []
        for r, c in zip(rows, ctxs):
            if r["metric"] == "num_em":
                sys_m = "Solve the math word problem using ONLY the provided context. Show brief steps and end your final line with: #### <final_number>"
                is_math.append(True)
            else:
                sys_m = "Answer the question using ONLY the provided context. Give the shortest exact answer (no explanation)."
                is_math.append(False)
            msgs = [{"role": "system", "content": sys_m}, {"role": "user", "content": f"Context:\n{c}\n\nQuestion: {r['question']}\nAnswer:"}]
            prompts.append(tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True))

        preds = []
        for i in range(0, len(prompts), 12):
            batch_p = prompts[i : i + 12]
            batch_m = is_math[i : i + 12]
            enc = tok(batch_p, padding=True, truncation=True, max_length=2560, return_tensors="pt").to("cuda")
            in_l = enc["input_ids"].shape[1]
            max_nt = 220 if any(batch_m) else 40
            with torch.inference_mode():
                gen = mod.generate(**enc, max_new_tokens=max_nt, do_sample=False, pad_token_id=tok.pad_token_id)
            dec = tok.batch_decode(gen[:, in_l:], skip_special_tokens=True)
            for is_m, txt in zip(batch_m, dec):
                if is_m:
                    preds.append(txt.split("####")[-1].strip() if "####" in txt else txt.strip())
                else:
                    preds.append(txt.strip().splitlines()[0] if txt.strip() else "")

        by_suite: dict[str, list[tuple[float, float, float]]] = {}
        for r, c, p in zip(rows, ctxs, preds):
            ret = len(WORD_RE.findall(c)) / max(len(WORD_RE.findall(r["context"])), 1)
            if r["metric"] == "num_em":
                pred_n = _extract_last_num(p)
                em = 1.0 if pred_n and pred_n == r["answers"][0] else 0.0
                f1 = em
            else:
                em, f1 = token_f1(p, r["answers"])
            by_suite.setdefault(r["suite"], []).append((em, f1, ret))

        suite_summary = {
            k: {
                "n": len(v),
                "em": round(float(np.mean([x[0] for x in v])), 4),
                "score": 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()
        }
        en_suites = [suite_summary[k]["score"] for k in ("ood_hotpotqa_rag", "ood_squad_v2", "ood_gsm8k_math", "ood_agent_json_qa") if k in suite_summary]
        all_suites = [v["score"] for v in suite_summary.values()]
        results[sname] = {
            "mean_5suite_score": round(float(np.mean(all_suites)), 4),
            "mean_4en_score": round(float(np.mean(en_suites)), 4),
            "by_suite": suite_summary,
        }
        print(f"  [{sname:28s}] 5-Suite={results[sname]['mean_5suite_score']:.4f} | 4-EN={results[sname]['mean_4en_score']:.4f} | { {k: v['score'] for k, v in suite_summary.items()} }", flush=True)

    del mod; gc.collect(); torch.cuda.empty_cache()
    return results


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--small-dir", type=str, required=True)
    parser.add_argument("--tiny-dir", type=str, required=True)
    parser.add_argument("--reader", type=str, default="microsoft/Phi-4-mini-instruct")
    parser.add_argument("--out-json", type=str, required=True)
    args = parser.parse_args()

    rows = build_5_suites()
    orig_ctxs = [r["context"] for r in rows]

    report: dict[str, Any] = {
        "reader": args.reader,
        "rates": {},
        "mbert_cpu_onnx_benchmark": bench_mbert_onnx_cpu(threads=4),
    }

    for rate in (0.50, 0.65):
        print(f"\n=== Evaluating 5 Zero-Touch Suites at rate={rate:.2f} ===", flush=True)
        ctxs_by_sys = {
            "uncompressed": orig_ctxs,
            "llmlingua2_mbert_178m": compress_contexts("microsoft/llmlingua-2-bert-base-multilingual-cased-meetingbank", orig_ctxs, rate, 320, 512),
            "llmlingua2_xlmr_560m": compress_contexts("microsoft/llmlingua-2-xlm-roberta-large-meetingbank", orig_ctxs, rate, 320, 512),
            "tamarillo_small_141m": compress_contexts(args.small_dir, orig_ctxs, rate, 2400, 3584),
            "tamarillo_tiny_en_32m": compress_contexts(args.tiny_dir, orig_ctxs, rate, 2400, 3584),
        }
        report["rates"][f"rate_{int(round(rate * 100))}"] = eval_with_reader(rows, ctxs_by_sys, args.reader)

    Path(args.out_json).write_text(json.dumps(report, indent=2), encoding="utf-8")
    print(f"\n[eval_pc_5suite] Wrote {args.out_json}", flush=True)


if __name__ == "__main__":
    main()