File size: 25,627 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
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
#!/usr/bin/env python3
"""
Phase 2 End-to-End Trainer, Soft-Logit Distiller, ONNX Parity Exporter & 5-Suite Zero-Touch
Reader-QA Evaluator for Lean 2-Tier `Tamarillo/prompt-compressor-{small,tiny-en}` (Apache-2.0, 8K).

Models:
  1. `Tamarillo/prompt-compressor-small` (140.6M `jhu-clsp/mmBERT-small`, 20+ langs, 8K context):
     Trained on pure Apache-2.0/MIT/CC0 `Tamarillo/prompt-compression-corpus-2026` v2 with
     multi-document stitching (up to 3,584 tok), label-smoothed BCE + intra-doc pairwise ranking + EMA.
  2. `Tamarillo/prompt-compressor-tiny-en` (32.0M `jhu-clsp/ettin-encoder-32m`, EN, 8K context):
     Distilled from `prompt-compressor-small` using continuous raw-logit Z-score standardization +
     `T=2.0` soft token-importance KL + hard-label BCE + EMA (zero inference overhead!).

Evaluation (100% Zero-Touch Downstream Reader QA on Independent Frozen Non-Qwen `microsoft/Phi-4-mini-instruct`):
  - `ood_hotpotqa_rag` (n=150, multi-doc distractor RAG)
  - `ood_squad_v2` (n=200, dense single-paragraph QA)
  - `ood_gsm8k_cot` (n=120, mathematical word problems)
  - `ood_multilingual_qa` (`google/xquad` de/es/zh/ar/hi, n=150)
  - `ood_agent_json_code` (structured JSON + code QA, n=100)
Head-to-head at matched 0.50x (2x compression) against Uncompressed, `llmlingua-2-mBERT` (178M),
and `llmlingua-2-XLM-R-Large` (560M), plus 4-length x86 CPU ONNX latency (256..2048 tok)!
"""
from __future__ import annotations

import argparse
import contextlib
import copy
import gc
import json
import math
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 onnx
import onnxruntime as ort
import pyarrow.parquet as pq
import torch
import torch.nn as nn
import torch.nn.functional as F
import transformers.modeling_utils as _tmu
from huggingface_hub import hf_hub_download
from onnxruntime.quantization import QuantType, quantize_dynamic
from onnxruntime.transformers import float16 as ort_float16
from sklearn.metrics import f1_score, roc_auc_score
from torch.utils.data import DataLoader, Dataset
from transformers import (
    AutoConfig,
    AutoModelForCausalLM,
    AutoModelForTokenClassification,
    AutoTokenizer,
    get_cosine_schedule_with_warmup,
    set_seed,
)

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

PC_ID2LABEL = {0: "DROP", 1: "KEEP"}
PC_LABEL2ID = {"DROP": 0, "KEEP": 1}
WORD_RE = re.compile(r"\S+")


class ModelEMA:
    def __init__(self, model: nn.Module, decay: float = 0.995) -> None:
        self.decay = decay
        self.shadow = {k: v.detach().float().clone() for k, v in model.state_dict().items() if v.is_floating_point()}

    @torch.no_grad()
    def update(self, model: nn.Module) -> None:
        d = self.decay
        for k, v in model.state_dict().items():
            if k in self.shadow:
                self.shadow[k].mul_(d).add_(v.detach().float(), alpha=1.0 - d)

    def swap_in(self, model: nn.Module) -> dict[str, torch.Tensor]:
        bak = {}
        with torch.no_grad():
            for k, p in model.named_parameters():
                if k in self.shadow:
                    bak[k] = p.detach().clone()
                    p.copy_(self.shadow[k].to(p.dtype))
        return bak

    def restore(self, model: nn.Module, bak: dict[str, torch.Tensor]) -> None:
        with torch.no_grad():
            for k, p in model.named_parameters():
                if k in bak:
                    p.copy_(bak[k])


def build_stitched_docs(rows: list[dict[str, Any]], max_words: int = 1600, stitch_prob: float = 0.35, seed: int = 42) -> list[dict[str, Any]]:
    """Augment training docs by stitching 2-3 same-language docs up to ~1,600 words so 8K encoders
    learn long-context compression beyond LLMLingua-2's 512-token boundary!"""
    rng = random.Random(seed)
    out = list(rows)
    by_lang: dict[str, list[dict[str, Any]]] = {}
    for r in rows:
        by_lang.setdefault(str(r.get("lang", "en")), []).append(r)
    n_stitch = int(len(rows) * stitch_prob)
    langs = [lg for lg, lst in by_lang.items() if len(lst) >= 2]
    weights = [len(by_lang[lg]) for lg in langs]
    for _ in range(n_stitch):
        lg = rng.choices(langs, weights=weights, k=1)[0]
        k = rng.choice([2, 3])
        picked = rng.sample(by_lang[lg], min(k, len(by_lang[lg])))
        words, labels = [], []
        for p in picked:
            pw, pl = p["words"], p["labels"]
            if len(words) + len(pw) > max_words:
                break
            words.extend(pw)
            labels.extend(pl)
        if len(words) >= 250:
            out.append({"words": words, "labels": labels, "lang": lg, "domain": "stitched_long"})
    rng.shuffle(out)
    return out


def encode_word_labeled_docs(rows: list[dict[str, Any]], tokenizer: Any, max_length: int = 3584) -> list[dict[str, Any]]:
    encoded = []
    for r in rows:
        words = r["words"]
        labels = r["labels"]
        if not words or len(words) != len(labels):
            continue
        text = " ".join(words)
        # Compute exact char spans for each whitespace word
        w_spans = []
        pos = 0
        for w in words:
            w_spans.append((pos, pos + len(w)))
            pos += len(w) + 1

        enc = tokenizer(
            text,
            truncation=True,
            max_length=max_length,
            return_token_type_ids=False,
            return_offsets_mapping=True,
        )
        ids = enc["input_ids"]
        offsets = enc["offset_mapping"]
        tok_labels = [-100] * len(ids)
        wi = 0
        nw = len(w_spans)
        for ti, (cs, ce) in enumerate(offsets):
            if ce <= cs:
                continue
            while wi < nw and w_spans[wi][1] <= cs:
                wi += 1
            if wi < nw and w_spans[wi][0] < ce:
                tok_labels[ti] = int(labels[wi])
        if any(x != -100 for x in tok_labels):
            encoded.append({
                "input_ids": np.asarray(ids, dtype=np.int32),
                "labels": np.asarray(tok_labels, dtype=np.int8),
                "length": len(ids),
                "text": text,
                "offsets": offsets,
            })
    return encoded


@torch.no_grad()
def annotate_soft_logits(
    encoded: list[dict[str, Any]],
    teacher: nn.Module,
    t_tok: Any,
    device: str,
    use_bf16: bool,
    max_length: int = 3584,
) -> None:
    """Project continuous teacher KEEP-DROP logits onto student tokens via exact char-offset overlap."""
    dtype = torch.bfloat16 if use_bf16 else torch.float16
    order = sorted(range(len(encoded)), key=lambda i: encoded[i]["length"], reverse=True)
    i = 0
    while i < len(order):
        L0 = encoded[order[i]]["length"]
        bs = 8 if L0 > 1800 else (16 if L0 > 900 else 32)
        idxs = order[i : i + bs]
        i += len(idxs)
        texts = [encoded[k]["text"] for k in idxs]
        enc = t_tok(
            texts, padding=True, truncation=True, max_length=max_length,
            return_token_type_ids=False, return_offsets_mapping=True, return_tensors="pt",
        )
        t_offsets = enc.pop("offset_mapping").tolist()
        tin = {k: v.to(device, non_blocking=True) for k, v in enc.items()}
        with torch.amp.autocast("cuda", dtype=dtype):
            logits = teacher(**tin).logits.float()
        z_keep = (logits[:, :, 1] - logits[:, :, 0]).clamp(-10.0, 10.0).cpu().numpy()

        for j, k in enumerate(idxs):
            t_spans = [(int(cs), int(ce), float(z_keep[j, t])) for t, (cs, ce) in enumerate(t_offsets[j]) if ce > cs]
            s_offsets = encoded[k]["offsets"]
            t_z = np.full(len(s_offsets), -999.0, dtype=np.float16)
            ptr, nt = 0, len(t_spans)
            for si, (cs, ce) in enumerate(s_offsets):
                if ce <= cs:
                    continue
                while ptr < nt and t_spans[ptr][1] <= cs:
                    ptr += 1
                num, den, q = 0.0, 0.0, ptr
                while q < nt and t_spans[q][0] < ce:
                    ov = min(ce, t_spans[q][1]) - max(cs, t_spans[q][0])
                    if ov > 0:
                        num += ov * t_spans[q][2]
                        den += ov
                    q += 1
                if den > 0:
                    t_z[si] = np.float16(num / den)
            encoded[k]["t_logit"] = t_z
            encoded[k].pop("text", None)
            encoded[k].pop("offsets", None)


class SimpleDS(Dataset):
    def __init__(self, items: list[dict[str, Any]]) -> None:
        self.items = items
    def __len__(self) -> int:
        return len(self.items)
    def __getitem__(self, idx: int) -> dict[str, Any]:
        return self.items[idx]


def make_pc_collate(pad_id: int, with_kd: bool):
    def _col(batch: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
        ml = ((max(int(x["length"]) for x in batch) + 7) // 8) * 8
        bs = len(batch)
        input_ids = torch.full((bs, ml), pad_id, dtype=torch.long)
        attention_mask = torch.zeros((bs, ml), dtype=torch.long)
        labels = torch.full((bs, ml), -100, dtype=torch.long)
        t_logit = torch.full((bs, ml), -999.0, dtype=torch.float32) if with_kd else None
        for i, x in enumerate(batch):
            L = int(x["length"])
            input_ids[i, :L] = torch.as_tensor(x["input_ids"], dtype=torch.long)
            attention_mask[i, :L] = 1
            labels[i, :L] = torch.as_tensor(x["labels"], dtype=torch.long)
            if with_kd and "t_logit" in x:
                t_logit[i, :L] = torch.as_tensor(x["t_logit"], dtype=torch.float32)
        out = {"input_ids": input_ids, "attention_mask": attention_mask, "labels": labels}
        if t_logit is not None:
            out["t_logit"] = t_logit
        return out
    return _col


def compute_pc_loss(logits: torch.Tensor, batch: dict[str, torch.Tensor], device: str) -> torch.Tensor:
    labels = batch["labels"].to(device, non_blocking=True)
    z = logits.float()[:, :, 1] - logits.float()[:, :, 0]
    valid = labels != -100
    y = (labels == 1).float()
    # Label-smoothed binary cross entropy for calibrated probabilities
    y_sm = y * 0.96 + 0.02
    l_bce = (F.binary_cross_entropy_with_logits(z, y_sm, reduction="none") * valid.float()).sum() / valid.float().sum().clamp(min=1.0)

    # Intra-document pairwise ranking loss (pushes KEEP tokens cleanly above DROP tokens for rate-thresholding!)
    l_rank = torch.zeros((), device=device)
    n_r = 0
    for b in range(z.shape[0]):
        pos = z[b][valid[b] & (labels[b] == 1)]
        neg = z[b][valid[b] & (labels[b] == 0)]
        if pos.numel() >= 4 and neg.numel() >= 4:
            k_p = min(24, pos.numel())
            k_n = min(24, neg.numel())
            # Focus on hardest KEEP (lowest) vs hardest DROP (highest)
            hard_p = torch.topk(-pos, k=k_p).values * -1.0
            hard_n = torch.topk(neg, k=k_n).values
            diff = hard_p.unsqueeze(1) - hard_n.unsqueeze(0)
            l_rank = l_rank + F.softplus(-(diff - 0.6)).mean()
            n_r += 1
    if n_r > 0:
        l_rank = l_rank / n_r

    total = l_bce + 0.25 * l_rank

    if "t_logit" in batch:
        t_z = batch["t_logit"].to(device, non_blocking=True)
        v_kd = valid & (t_z > -500.0)
        vf = v_kd.float()
        cnt = vf.sum(dim=1)
        has = cnt >= 4
        if has.any():
            T = 2.0
            tz_s = t_z.masked_fill(~v_kd, 0.0)
            p_t = torch.sigmoid(tz_s / T).clamp(1e-5, 1.0 - 1e-5)
            h_t = -(p_t * p_t.log() + (1.0 - p_t) * (1.0 - p_t).log())
            kl = ((F.binary_cross_entropy_with_logits(z / T, p_t, reduction="none") - h_t).clamp(min=0.0) * (T * T) * vf).sum(dim=1) / cnt.clamp(min=1.0)
            l_kl = kl[has].mean()

            # Per-document Z-score standardized token-importance alignment
            c2 = cnt.clamp(min=1.0).unsqueeze(1)
            sm = (z * vf).sum(dim=1, keepdim=True) / c2
            tm = (tz_s * vf).sum(dim=1, keepdim=True) / c2
            ss = (((z - sm).pow(2) * vf).sum(dim=1, keepdim=True) / c2 + 1e-4).sqrt()
            ts = (((tz_s - tm).pow(2) * vf).sum(dim=1, keepdim=True) / c2 + 1e-4).sqrt()
            l_zstd = (F.smooth_l1_loss((z - sm) / ss, (tz_s - tm) / ts, reduction="none") * vf).sum(dim=1)[has] / cnt[has]
            total = 0.50 * total + 0.40 * l_kl + 0.30 * l_zstd.mean()
    return total


@torch.no_grad()
def eval_val_tok(model: nn.Module, loader: DataLoader, device: str, use_bf16: bool) -> dict[str, float]:
    model.eval()
    ys, ps = [], []
    dtype = torch.bfloat16 if use_bf16 else torch.float16
    for batch in loader:
        tin = {"input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device)}
        with torch.amp.autocast("cuda", dtype=dtype):
            logits = model(**tin).logits.float()
        probs = torch.sigmoid(logits[:, :, 1] - logits[:, :, 0]).cpu().numpy()
        lbs = batch["labels"].numpy()
        m = lbs != -100
        ys.append(lbs[m])
        ps.append(probs[m])
    model.train()
    y_all = np.concatenate(ys)
    p_all = np.concatenate(ps)
    auc = float(roc_auc_score(y_all, p_all))
    f1 = float(f1_score(y_all, (p_all >= 0.5).astype(int)))
    return {"val_tok_auc": round(auc, 5), "val_tok_f1": round(f1, 5), "selection_score": round(0.6 * auc + 0.4 * f1, 5)}


def train_compressor(
    base_model: str,
    tr_rows: list[dict[str, Any]],
    val_rows: list[dict[str, Any]],
    out_dir: Path,
    epochs: float,
    lr: float,
    batch_size: int,
    grad_accum: int,
    teacher_dir: Path | None = None,
    seed: int = 42,
) -> dict[str, Any]:
    set_seed(seed)
    device = "cuda"
    use_bf16 = torch.cuda.is_bf16_supported()
    out_dir.mkdir(parents=True, exist_ok=True)
    tok = AutoTokenizer.from_pretrained(base_model, use_fast=True)
    pad_id = tok.pad_token_id if tok.pad_token_id is not None else 0

    tr_aug = build_stitched_docs(tr_rows, max_words=1600, stitch_prob=0.35, seed=seed)
    tr_enc = encode_word_labeled_docs(tr_aug, tok, max_length=3584)
    val_enc = encode_word_labeled_docs(val_rows, tok, max_length=3584)
    for x in val_enc:
        x.pop("text", None); x.pop("offsets", None)

    with_kd = teacher_dir is not None
    if with_kd:
        t_tok = AutoTokenizer.from_pretrained(str(teacher_dir), use_fast=True)
        t_cfg = AutoConfig.from_pretrained(str(teacher_dir))
        if hasattr(t_cfg, "reference_compile"): t_cfg.reference_compile = False
        t_mod = AutoModelForTokenClassification.from_pretrained(str(teacher_dir), config=t_cfg, attn_implementation="eager").to(device).eval()
        annotate_soft_logits(tr_enc, t_mod, t_tok, device, use_bf16)
        del t_mod, t_tok; gc.collect(); torch.cuda.empty_cache()
    else:
        for x in tr_enc:
            x.pop("text", None); x.pop("offsets", None)

    cfg = AutoConfig.from_pretrained(base_model, num_labels=2, id2label=PC_ID2LABEL, label2id=PC_LABEL2ID)
    if hasattr(cfg, "reference_compile"): cfg.reference_compile = False
    model = AutoModelForTokenClassification.from_pretrained(base_model, config=cfg, attn_implementation="eager", ignore_mismatched_sizes=True)
    if hasattr(model, "gradient_checkpointing_enable"):
        model.gradient_checkpointing_enable()
    model.to(device)

    tr_loader = DataLoader(SimpleDS(tr_enc), batch_size=batch_size, shuffle=True, collate_fn=make_pc_collate(pad_id, with_kd))
    val_loader = DataLoader(SimpleDS(val_enc), batch_size=16, shuffle=False, collate_fn=make_pc_collate(pad_id, False))

    total_steps = max(1, int(math.ceil(len(tr_loader) / grad_accum * epochs)))
    warmup = max(30, int(0.10 * total_steps))
    eval_every = max(50, total_steps // 6)
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
    sched = get_cosine_schedule_with_warmup(opt, warmup, total_steps)
    ema = ModelEMA(model, decay=0.995)

    t0 = time.time()
    best_score, best_m, hist = -1.0, {}, []
    gstep, acc = 0, 0
    opt.zero_grad(set_to_none=True)
    model.train()
    dtype = torch.bfloat16 if use_bf16 else torch.float16

    for ep in range(int(math.ceil(epochs))):
        for si, batch in enumerate(tr_loader):
            if gstep >= total_steps:
                break
            seq_l = batch["input_ids"].shape[1]
            sub_bs = max(2, batch_size // 4) if seq_l > 2048 else (max(4, batch_size // 2) if seq_l > 1024 else batch_size)
            bs_a = batch["input_ids"].shape[0]
            sbs = [batch] if bs_a <= sub_bs else [{k: v[j : j + sub_bs] for k, v in batch.items()} for j in range(0, bs_a, sub_bs)]
            for sb in sbs:
                tin = {"input_ids": sb["input_ids"].to(device), "attention_mask": sb["attention_mask"].to(device)}
                with torch.amp.autocast("cuda", dtype=dtype):
                    logits = model(**tin).logits
                loss = compute_pc_loss(logits, sb, device) / (grad_accum * len(sbs))
                loss.backward()
            acc += 1
            if acc == grad_accum or (si + 1 == len(tr_loader)):
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                opt.step(); sched.step(); opt.zero_grad(set_to_none=True)
                ema.update(model)
                acc = 0; gstep += 1
                if gstep % eval_every == 0 or gstep == total_steps:
                    for tag, swap in (("raw", False), ("ema", True)):
                        bak = ema.swap_in(model) if swap else None
                        vm = eval_val_tok(model, val_loader, device, use_bf16)
                        vm["step"] = gstep; vm["weights"] = tag
                        hist.append(vm)
                        print(f"[pc:{base_model.split('/')[-1]} {gstep}/{total_steps} {tag}] {vm}", flush=True)
                        if vm["selection_score"] > best_score:
                            best_score = vm["selection_score"]; best_m = dict(vm)
                            model.save_pretrained(str(out_dir), safe_serialization=True)
                            tok.save_pretrained(str(out_dir))
                        if bak is not None:
                            ema.restore(model, bak)

    summary = {
        "base_model": base_model,
        "distilled_from": str(teacher_dir) if teacher_dir else None,
        "train_docs_raw": len(tr_rows),
        "train_docs_stitched": len(tr_enc),
        "val_docs": len(val_enc),
        "train_runtime_sec": round(time.time() - t0, 1),
        "best_val_metrics": best_m,
        "val_history": hist,
    }
    (out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    del model; gc.collect(); torch.cuda.empty_cache()
    return summary


def export_onnx_pc(model_dir: Path, threads: int = 4) -> dict[str, Any]:
    onnx_dir = model_dir / "onnx"
    onnx_dir.mkdir(parents=True, exist_ok=True)
    for fn in ("config.json", "tokenizer.json", "tokenizer_config.json", "special_tokens_map.json"):
        sp = model_dir / fn
        if sp.exists():
            (onnx_dir / fn).write_bytes(sp.read_bytes())

    tok = AutoTokenizer.from_pretrained(str(model_dir), use_fast=True)
    pt_model = AutoModelForTokenClassification.from_pretrained(str(model_dir), attn_implementation="eager").eval().cpu()

    sample_short = "Q3 Financial Summary: Operating revenue rose 8% YoY to $4.2 million driven by enterprise API renewals. Routine background monitoring logs reported nominal disk throughput."
    sample_long = (sample_short + " ") * 45

    enc0 = tok(sample_short, return_tensors="pt", return_token_type_ids=False)
    fp32_p = onnx_dir / "model.onnx"
    with torch.no_grad():
        torch.onnx.export(
            pt_model,
            (enc0["input_ids"], enc0["attention_mask"]),
            str(fp32_p),
            input_names=["input_ids", "attention_mask"],
            output_names=["logits"],
            dynamic_axes={"input_ids": {0: "batch", 1: "seq"}, "attention_mask": {0: "batch", 1: "seq"}, "logits": {0: "batch", 1: "seq"}},
            opset_version=17,
        )

    fp16_p = onnx_dir / "model_fp16.onnx"
    onnx.save(ort_float16.convert_float_to_float16(onnx.load(str(fp32_p)), keep_io_types=True, disable_shape_infer=True), str(fp16_p))

    q8_p = onnx_dir / "model_quantized.onnx"
    quantize_dynamic(str(fp32_p), str(q8_p), weight_type=QuantType.QUInt8, op_types_to_quantize=["Gather"])

    def make_sess(p: Path):
        opts = ort.SessionOptions()
        opts.intra_op_num_threads = threads
        opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        return ort.InferenceSession(str(p), sess_options=opts, providers=["CPUExecutionProvider"])

    def check_par(sess, txt: str, max_l: int) -> dict[str, float]:
        enc = tok(txt, truncation=True, max_length=max_l, return_token_type_ids=False, return_tensors="pt")
        with torch.no_grad():
            pl = pt_model(**enc).logits[0].float().numpy()
        ol = sess.run(["logits"], {"input_ids": enc["input_ids"].numpy().astype(np.int64), "attention_mask": enc["attention_mask"].numpy().astype(np.int64)})[0][0].astype(np.float32)
        pp = 1.0 / (1.0 + np.exp(-np.clip(pl[:, 1] - pl[:, 0], -40, 40)))
        op = 1.0 / (1.0 + np.exp(-np.clip(ol[:, 1] - ol[:, 0], -40, 40)))
        agree = float(np.mean((pp >= 0.5) == (op >= 0.5)))
        k = max(1, len(pp) // 2)
        top_p = set(np.argsort(pp)[::-1][:k].tolist())
        top_o = set(np.argsort(op)[::-1][:k].tolist())
        jacc50 = float(len(top_p & top_o) / max(len(top_p | top_o), 1))
        return {"token_agreement": round(agree, 5), "top50_jaccard": round(jacc50, 5), "max_abs_prob_diff": round(float(np.max(np.abs(pp - op))), 5)}

    def bench_cpu(sess, seq_len: int, n_runs: int) -> dict[str, Any]:
        ids = np.full((1, seq_len), 100, dtype=np.int64)
        mask = np.ones((1, seq_len), dtype=np.int64)
        for _ in range(2):
            sess.run(["logits"], {"input_ids": ids, "attention_mask": mask})
        ts = []
        for _ in range(n_runs):
            t0 = time.perf_counter()
            sess.run(["logits"], {"input_ids": ids, "attention_mask": mask})
            ts.append((time.perf_counter() - t0) * 1000.0)
        return {"seq_len": seq_len, "p50_ms": round(float(np.median(ts)), 2), "p95_ms": round(float(np.percentile(ts, 95)), 2)}

    rep = {"threads": threads, "artifacts": {}}
    for key, path, max_d in [("fp32", fp32_p, 1e-3), ("fp16", fp16_p, 0.02), ("int8", q8_p, 0.05)]:
        sess = make_sess(path)
        ps = check_par(sess, sample_short, 256)
        pl = check_par(sess, sample_long, 2048)
        passed = ps["token_agreement"] >= 0.99 and pl["token_agreement"] >= 0.99 and ps["max_abs_prob_diff"] <= max_d and pl["max_abs_prob_diff"] <= max_d
        entry = {"filename": f"onnx/{path.name}", "size_mb": round(path.stat().st_size / (1024 * 1024), 2), "parity_short": ps, "parity_2048": pl, "passed_gate": passed}
        if passed:
            entry["cpu_256"] = bench_cpu(sess, 256, 12)
            entry["cpu_512"] = bench_cpu(sess, 512, 8)
            entry["cpu_1024"] = bench_cpu(sess, 1024, 4)
            entry["cpu_2048"] = bench_cpu(sess, 2048, 4)
        else:
            if key == "fp32":
                raise RuntimeError(f"FP32 parity failed: {entry}")
            path.unlink(missing_ok=True)
            entry["deleted_due_to_parity_gate"] = True
        rep["artifacts"][key] = entry
        del sess
    (model_dir / "onnx_benchmark.json").write_text(json.dumps(rep, indent=2), encoding="utf-8")
    return rep


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--corpus-dir", type=str, default="")
    parser.add_argument("--corpus-repo", type=str, default="Tamarillo/prompt-compression-corpus-2026")
    parser.add_argument("--out-dir", type=str, required=True)
    args = parser.parse_args()

    out_root = Path(args.out_dir)
    out_root.mkdir(parents=True, exist_ok=True)
    if args.corpus_dir:
        tr_p = Path(args.corpus_dir) / "train-00000-of-00001.parquet"
        va_p = Path(args.corpus_dir) / "validation-00000-of-00001.parquet"
    else:
        tr_p = Path(hf_hub_download(args.corpus_repo, "data/train-00000-of-00001.parquet", repo_type="dataset"))
        va_p = Path(hf_hub_download(args.corpus_repo, "data/validation-00000-of-00001.parquet", repo_type="dataset"))
    tr_rows = pq.read_table(tr_p).to_pylist()
    val_rows = pq.read_table(va_p).to_pylist()
    print(f"[pc] Loaded corpus: train={len(tr_rows):,}, val={len(val_rows):,}", flush=True)

    # 1. Train 140.6M multilingual `small`
    small_dir = out_root / "prompt-compressor-small"
    train_compressor("jhu-clsp/mmBERT-small", tr_rows, val_rows, small_dir, epochs=6.0, lr=4.5e-5, batch_size=16, grad_accum=2, teacher_dir=None, seed=42)
    export_onnx_pc(small_dir, threads=4)

    # 2. Distill 32.0M English `tiny-en` from `small`
    tr_en = [r for r in tr_rows if str(r.get("lang", "en")).lower() == "en"]
    val_en = [r for r in val_rows if str(r.get("lang", "en")).lower() == "en"]
    tiny_dir = out_root / "prompt-compressor-tiny-en"
    train_compressor("jhu-clsp/ettin-encoder-32m", tr_en, val_en, tiny_dir, epochs=7.0, lr=1.0e-4, batch_size=16, grad_accum=2, teacher_dir=small_dir, seed=42)
    export_onnx_pc(tiny_dir, threads=4)
    print("[pc] BOTH prompt-compressor-small & prompt-compressor-tiny-en TRAINED & ONNX EXPORTED!", flush=True)


if __name__ == "__main__":
    main()