File size: 4,620 Bytes
d82e576
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Reference row for the leaderboard: TF-IDF over code tokens and one logistic regression per question.

A specialist fitted on `train`: it reads `code` only, never the task or the question text. C is picked per
question by validation log loss. Writes test answers in the System One answer shape, one JSON object per
case, with the wall-clock latency of vectorising and answering that case on its own.

    uv run --no-project --with pyarrow==26.0.0 --with scikit-learn==1.9.1 \
      python3 baseline_decisions.py [--out baselines/tfidf-logreg.test.jsonl]
Then: python3 score_decisions.py baselines/tfidf-logreg.test.jsonl
"""
import argparse
import json
import platform
import time
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
from joblib import Parallel, delayed
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import log_loss

HERE = Path(__file__).resolve().parent
# Identifiers, then single punctuation characters, so `!`, `?.`, `==` pieces and quote styles stay visible.
TOKEN_PATTERN = r"[A-Za-z_$][A-Za-z0-9_$]*|[^\sA-Za-z0-9_$]"
C_GRID = (0.3, 1.0, 3.0, 10.0, 30.0, 100.0)


def load(split: str) -> list[dict]:
    return pq.read_table(HERE / "decisions" / f"{split}.parquet", columns=["id", "state", "questions", "gold"]).to_pylist()


def fit_one(c: float, x_train, y_train, x_val, y_val) -> tuple[float, LogisticRegression]:
    model = LogisticRegression(C=c, max_iter=5000).fit(x_train, y_train)
    return log_loss(y_val, model.predict_proba(x_val), labels=model.classes_), model


def fit(x_train, y_train, x_val, y_val) -> LogisticRegression:
    fitted = Parallel(n_jobs=len(C_GRID))(delayed(fit_one)(c, x_train, y_train, x_val, y_val) for c in C_GRID)
    return min(fitted, key=lambda pair: pair[0])[1]


def answer(question: dict, model: LogisticRegression, x) -> dict:
    columns = {label: j for j, label in enumerate(model.classes_)}
    probabilities = model.predict_proba(x)[0]
    if question["type"] == "noul":
        return {"type": "noul", "noul": float(probabilities[columns["true"]]) if "true" in columns else 0.0}
    options = list(question["criteria"]) if question["type"] == "choice" else [str(i) for i in range(len(question["criteria"]))]
    return {"type": question["type"],
            "probabilities": {o: float(probabilities[columns[o]]) if o in columns else 0.0 for o in options}}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--out", type=Path, default=HERE / "baselines" / "tfidf-logreg.test.jsonl")
    args = parser.parse_args()
    started = time.perf_counter()
    cases = {split: load(split) for split in ("train", "validation", "test")}
    questions = json.loads(cases["test"][0]["questions"])
    code = {split: [json.loads(c["state"])["code"] for c in rows] for split, rows in cases.items()}
    vectorizer = TfidfVectorizer(token_pattern=TOKEN_PATTERN, lowercase=False, ngram_range=(1, 2), min_df=2, sublinear_tf=True)
    x = {"train": vectorizer.fit_transform(code["train"])}
    for split in ("validation", "test"):
        x[split] = vectorizer.transform(code[split])

    def targets(split: str, name: str) -> np.ndarray:
        return np.array([json.loads(c["gold"])[name]["label"] for c in cases[split]])

    models, chosen = {}, {}
    for name in questions:
        models[name] = fit(x["train"], targets("train", name), x["validation"], targets("validation", name))
        chosen[name] = float(models[name].C)
    fit_seconds = time.perf_counter() - started

    args.out.parent.mkdir(exist_ok=True)
    latencies = []
    with args.out.open("w") as handle:
        for case, text in zip(cases["test"], code["test"], strict=True):
            tick = time.perf_counter()
            features = vectorizer.transform([text])
            answers = {name: answer(question, models[name], features) for name, question in questions.items()}
            latency = 1000 * (time.perf_counter() - tick)
            latencies.append(latency)
            handle.write(json.dumps({"id": case["id"], "answers": answers, "latency_ms": round(latency, 3)}) + "\n")
    print(json.dumps({
        "out": str(args.out),
        "vocabulary": len(vectorizer.vocabulary_),
        "C_by_question": chosen,
        "fit_seconds": round(fit_seconds),
        "p50_latency_ms": round(float(np.median(latencies)), 2),
        "machine": f"{platform.machine()}, {platform.processor() or platform.system()}",
    }, indent=1))


if __name__ == "__main__":
    main()