ecbs5200-jev-benchmark / code /embedding_control.py
earino's picture
Release for 'Fine-Tune If You Can' (SemIf, GLM-5.3, retrieval, controls, learning curves); verified reproduction
0164c03 verified
Raw History Blame Contribute Delete
6.52 kB
"""
Features control for the Jev paper: is TF-IDF + Jev's lift specific to Jev's probabilities, or would any dense
semantic representation of the complaint do the same?
===========================================================================================================
Identical protocol to `jev_extended.py features`: fit set = train + test (79,278); model selection on the same
stratified 10% slice (seed 42); the same logistic-regression grid (C in {1,10,30,100} x class_weight x feature
weight w in {0.1,0.3}); refit on the full fit set; the evaluation split is scored once. The only change: Jev's
113-dim log-probability vector is replaced by a 768-dim sentence embedding (sentence-transformers
`all-mpnet-base-v2`, mean-pooled, L2-normalised, then standardised like the Jev features). The grid was fixed
before any evaluation-split scoring.
uv run --no-project --with numpy --with scikit-learn --with scipy --with joblib --with datasets \\
--with sentence-transformers python verification/embedding_control.py
"""
import json
import sys
import time
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "verification"))
from utils.data_utils import load_course_data, NUM_LABELS
from jev_benchmark import SEED, macro_f1
EMB_MODEL = "sentence-transformers/all-mpnet-base-v2"
OUT = ROOT / "verification" / "jev_benchmark_artifacts"
DEV_FRACTION = 0.1
def embed(texts, cache):
if cache.exists():
return np.load(cache)["emb"]
import torch
from sentence_transformers import SentenceTransformer
dev = "mps" if torch.backends.mps.is_available() else "cpu"
m = SentenceTransformer(EMB_MODEL, device=dev)
t0 = time.time()
E = m.encode(texts, batch_size=128, normalize_embeddings=True, show_progress_bar=False, convert_to_numpy=True)
print(f" embedded {len(texts):,} texts on {dev} in {time.time() - t0:.0f}s")
np.savez_compressed(cache, emb=E.astype(np.float32))
return E
def main():
from joblib import Parallel, delayed
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
train_ds, val_ds, test_ds = load_course_data()
fit_texts = list(train_ds["text"]) + list(test_ds["text"])
y_fit = np.concatenate([train_ds["label"], test_ds["label"]])
val_texts, y_val = list(val_ds["text"]), np.array(val_ds["label"])
E_fit = embed(fit_texts, OUT / "embeddings_mpnet_fit.npz")
E_val = embed(val_texts, OUT / "embeddings_mpnet_val.npz")
idx = np.arange(len(y_fit))
tr, dev = train_test_split(idx, test_size=DEV_FRACTION, stratify=y_fit, random_state=SEED)
def build(kind, rows, fitted=None, w=None):
texts = [fit_texts[i] for i in rows] if rows is not None else val_texts
E = E_fit[rows] if rows is not None else E_val
fitted = dict(fitted or {})
parts = []
if kind == "tfidf+emb":
if "tfidf" not in fitted:
fitted["tfidf"] = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit(texts)
parts.append(fitted["tfidf"].transform(texts))
if "scaler" not in fitted:
fitted["scaler"] = StandardScaler().fit(E)
parts.append(csr_matrix(fitted["scaler"].transform(E) * (w if w is not None else 1.0)))
return hstack(parts).tocsr(), fitted
def fit_lr(X, y, C, cw):
return LogisticRegression(C=C, class_weight=cw, max_iter=2000, solver="lbfgs").fit(X, y)
# C in {0.001, 0.003} added after pass 2 showed the embeddings-only model selecting C=0.01 (the grid edge)
grids = {"emb": [dict(C=C, class_weight=cw) for C in (0.001, 0.003, 0.01, 0.1, 1.0, 10.0) for cw in (None, "balanced")],
"tfidf+emb": [dict(C=C, class_weight=cw, w=w) for C in (1.0, 10.0, 30.0, 100.0)
for cw in (None, "balanced") for w in (0.01, 0.03, 0.1, 0.3)]}
# w in {0.01, 0.03} added after pass 1 selected w=0.1 (the grid edge); a 768-dim embedding carries ~2.6x the
# feature norm of Jev's 113 dims at equal w. Pass-1 outputs are kept as *_pass1.*
def dev_score(kind, cfg):
Xtr, fitted = build(kind, tr, w=cfg.get("w"))
Xdv, _ = build(kind, dev, fitted, w=cfg.get("w"))
return kind, cfg, macro_f1(y_fit[dev], fit_lr(Xtr, y_fit[tr], cfg["C"], cfg["class_weight"]).predict(Xdv))
cache_p = OUT / "embedding_control_selection_cache.json"
cache = json.loads(cache_p.read_text()) if cache_p.exists() else {}
key = lambda k, c: f"{k} {json.dumps(c, sort_keys=True)}"
jobs = [(k, c) for k, cfgs in grids.items() for c in cfgs if key(k, c) not in cache]
print(f"Model selection: {len(jobs)} fits on {len(tr):,} rows, scored on {len(dev):,}...")
t0 = time.time()
for k, c, f1 in Parallel(n_jobs=8)(delayed(dev_score)(k, c) for k, c in jobs):
cache[key(k, c)] = f1
cache_p.write_text(json.dumps(cache, indent=1))
print(f" selection done in {(time.time() - t0) / 60:.0f} min")
best = {}
for k, cfgs in grids.items():
for c in cfgs:
f1 = cache[key(k, c)]
print(f" {k:<10} {json.dumps(c):<55} selection-slice macro F1 {f1:.4f}")
if k not in best or f1 > best[k][1]:
best[k] = (c, f1)
def final(kind):
cfg = best[kind][0]
Xfit, fitted = build(kind, idx, w=cfg.get("w"))
Xv, _ = build(kind, None, fitted, w=cfg.get("w"))
clf = fit_lr(Xfit, y_fit, cfg["C"], cfg["class_weight"])
full = np.zeros((len(y_val), NUM_LABELS)); full[:, clf.classes_] = clf.predict_proba(Xv)
return kind, full
finals = dict(Parallel(n_jobs=2)(delayed(final)(k) for k in grids))
for k, pr in finals.items():
p = pr.argmax(-1)
print(f" EVAL {k:<10} acc {(p == y_val).mean():.3f} macro F1 {macro_f1(y_val, p):.3f} selected {best[k][0]}")
np.savez_compressed(OUT / "embedding_control_val_probs.npz", labels=y_val, emb=finals["emb"],
tfidf_emb=finals["tfidf+emb"])
(OUT / "embedding_control_selected.json").write_text(json.dumps(
{k: {**best[k][0], "selection_macro_f1": best[k][1]} for k in best}, indent=2))
print(" saved embedding_control_val_probs.npz")
if __name__ == "__main__":
main()