File size: 9,102 Bytes
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
 
b045445
 
296ef60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0164c03
 
296ef60
 
20aeae0
296ef60
20aeae0
296ef60
 
0164c03
 
 
 
 
 
 
 
 
 
 
b045445
 
0164c03
 
 
 
 
 
 
b045445
 
0164c03
 
 
07c63a7
 
 
 
 
 
 
 
 
296ef60
 
 
 
07c63a7
 
 
 
 
 
296ef60
 
9ae0d6b
 
 
b045445
9ae0d6b
 
 
296ef60
 
 
 
 
 
 
 
b045445
0164c03
 
 
 
 
 
 
296ef60
 
 
 
 
9ae0d6b
0164c03
 
 
296ef60
 
 
 
 
 
 
 
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
"""
Assemble the public release for the Jev benchmark paper into a directory (default: ./release_staging).
Everything needed to regenerate the paper's tables and figures without training or API calls.

    uv run --no-project --with numpy --with scikit-learn --with matplotlib --with huggingface_hub \\
        --with datasets python papers/jev_benchmark/build_release.py [OUT_DIR]
"""

import hashlib
import json
import shutil
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
ART = ROOT / "verification" / "jev_benchmark_artifacts"
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(ROOT))
import analysis  # build-repo mode (no --release flag)

OUT = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else HERE / "release_staging"


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def main():
    from huggingface_hub import HfApi
    from utils.data_utils import load_course_data
    if OUT.exists():
        shutil.rmtree(OUT)
    for d in ("data", "utils", "code", "criteria", "jev_responses", "predictions", "results"):
        (OUT / d).mkdir(parents=True)

    # Splits, labels and the loader (all already public in the course repository)
    for f in ("label_list.json", "label_merge_mapping.json", "train_indices.json", "val_indices.json"):
        shutil.copy(ROOT / "data" / f, OUT / "data" / f)
    shutil.copy(ROOT / "utils" / "data_utils.py", OUT / "utils" / "data_utils.py")
    (OUT / "utils" / "__init__.py").write_text("")

    # Code
    V = ROOT / "verification"
    for f in (V / "jev_benchmark.py", V / "jev_extended.py", V / "semif_benchmark.py", V / "glm_benchmark.py",
              V / "embedding_control.py", V / "features_controls.py", V / "features_controls_v2.py", V / "knn_vote.py",
              V / "semif_features.py", HERE / "analysis.py", HERE / "make_tables.py", HERE / "build_release.py",
              HERE / "trace_numbers.py"):
        shutil.copy(f, OUT / "code" / f.name)

    # Criteria and the fixed training dev slice
    for f in ("v1.json", "v2.json", "v1instr.json", "train_dev_idx.json"):
        shutil.copy(ROOT / "verification" / "jev_criteria" / f, OUT / "criteria" / f)

    # Raw Jev responses (probabilities, confidence, latency, tokens, request id)
    for f in sorted(ART.glob("*_responses.jsonl")):
        shutil.copy(f, OUT / "jev_responses" / f.name)

    # Every system's validation predictions in one aligned file
    y, tiers, systems, conf, comps = analysis.load_systems()
    _, val_ds, _ = load_course_data()
    texts = list(val_ds["text"])
    arrays = {"labels": y, "tiers": tiers.astype("U4"),
              "text_sha256": np.array([hashlib.sha256(t.encode()).hexdigest() for t in texts]),
              "val_row_index": np.arange(len(y))}
    for name, key in analysis.SYSTEM_KEYS.items():
        if name not in systems:   # open-reproduction variants are included as their full-validation runs land
            continue
        p, pr = systems[name]
        arrays[f"{key}_preds"] = p.astype(np.int16)
        arrays[f"{key}_probs"] = pr.astype(np.float64)
        if name in conf:
            arrays[f"{key}_confidence"] = np.asarray(conf[name], dtype=np.float64)
    np.savez_compressed(OUT / "predictions" / "val_predictions_all_systems.npz", **arrays)

    # SemIf (open reproduction): runner, raw option logits, composed probabilities, manifests, summary
    (OUT / "results" / "semif").mkdir(parents=True, exist_ok=True)
    for pat in ("semif-qwen3.5-4b_*_val_*", "semif-qwen3.5-4b_*_results_full.json", "semif-qwen3.5-4b_*_manifest_full.json",
                "semif-qwen3.5-4b_*_fit20000_probs.npz", "SUMMARY.md"):
        for f in sorted(analysis.SEMIF.glob(pat)):
            if f.is_file():
                shutil.copy(f, OUT / "results" / "semif" / f.name)

    # GLM-5.3 (zero-shot and 20 retrieved examples): raw answers, manifests, results
    (OUT / "results" / "glm").mkdir(parents=True, exist_ok=True)
    for pat in ("glm-5.3*_val_responses.jsonl", "glm-5.3*_val_probs.npz", "glm-5.3*_manifest_full.json",
                "glm-5.3*_results_full.json", "glm-5.3*_truncated_first_attempt.jsonl",
                "discarded_maxtok64_traindev_responses.jsonl"):
        for f in sorted(analysis.GLM_DIR.glob(pat)):
            shutil.copy(f, OUT / "results" / "glm" / f.name)

    # Feature controls, learning curves, selection caches, nearest-neighbour vote, retrieval neighbours
    for f in ("controls_results.json", "controls_v2_results.json", "controls_selection_cache.json",
              "controls_v2_selection_cache.json", "embedding_control_selection_cache.json",
              "embedding_control_selected.json", "embedding_control_selected_pass1.json",
              "semif_features_fit20000_results.json", "retrieval_neighbours_val.npz",
              "embedding_control_val_probs_pass1.npz"):
        if (ART / f).exists():
            shutil.copy(ART / f, OUT / "results" / f)

    # Results, token-usage ledger and latency. Monetary fields are dropped; the paper reports token counts only.
    def strip_costs(x):
        if isinstance(x, dict):
            return {k: strip_costs(v) for k, v in x.items()
                    if not any(w in k for w in ("cost", "price", "billed"))}
        if isinstance(x, list):
            return [strip_costs(v) for v in x]
        return x
    for f in ("latency_jev.json", "latency_probes.json", "jev-1.13.0_manifest_full.json",
              "jev-1.13.0_results_full.json", "jev-1.13.0_features_results.json",
              "jev-1.13.0_features_results_pass1.json", "jev-1.13.0_features_selection_cache.json",
              "jev-1.13.0_criteria_v1_val_results.json", "jev-1.13.0_criteria_v1instr_val_results.json"):
        if (ART / f).exists():
            (OUT / "results" / f).write_text(json.dumps(strip_costs(json.loads((ART / f).read_text())), indent=2))
    ledger = json.loads((ART / "spend_ledger.json").read_text())
    usage = {"files": [{k: v for k, v in r.items() if k in ("file", "requests", "input_tokens")}
                       for r in ledger["files"]],
             "total_requests": ledger["total_requests"], "total_input_tokens": ledger["total_input_tokens"]}
    (OUT / "results" / "token_usage.json").write_text(json.dumps(usage, indent=2))
    shutil.copy(HERE / "numbers.json", OUT / "results" / "numbers_reference.json")

    # Pinned environment: the package versions this release was built and verified with
    import platform
    from importlib.metadata import version
    pkgs = ["numpy", "scikit-learn", "matplotlib", "huggingface_hub", "datasets", "tokenizers"]
    env = {"python": platform.python_version(), **{k: version(k) for k in pkgs}}
    (OUT / "requirements.txt").write_text("".join(f"{k}=={env[k]}\n" for k in pkgs))

    # Manifest: provenance and checksums
    api = HfApi()
    ds = api.dataset_info("determined-ai/consumer_complaints_medium")
    comparators = []
    for name, repo, fname in comps:
        info = api.model_info(repo)
        comparators.append({"name": name, "repo": repo, "file": fname, "revision": info.sha})
    manifest = {
        "paper": "Zero-Shot Classifiers, Retrieved Examples and Trained Models "
                 "on a 113-Class Complaint Taxonomy",
        "glm": {"model": "glm-5.3", "access": "LunaRoute gateway (gw.lunaroute.com), OpenAI-compatible chat completions",
                "settings": "temperature 0, reasoning on, 16,384-token budget; truncated answers re-requested once at 65,536",
                "retrieval": "20 nearest fit-set complaints by cosine similarity of all-mpnet-base-v2 embeddings"},
        "semif": {"repo": "https://github.com/TheoLeeCJ/SemIf", "commit": "1f2dea3e25379f9dfc98cb83c324f00ab5deda37",
                  "model": "Qwen/Qwen3.5-4B", "revision": "851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a",
                  "backend": "mlx", "variants_included": [k for k in analysis.SEMIF_FILES if k in systems]},
        "jev_model": "jev-1.13.0", "typesafe_sdk": "0.7.0",
        "dataset": {"repo": "determined-ai/consumer_complaints_medium", "revision": ds.sha},
        "evaluation_split": "canonical validation split (data/val_indices.json after label mapping), 6,430 rows",
        "comparators": comparators,
        "prediction_file_keys": analysis.SYSTEM_KEYS,
        "environment": env,
        "reproduce": "pip install -r requirements.txt && python code/analysis.py --release . && "
                     "python code/make_tables.py --release .   (writes results/numbers.json, results/figures/, "
                     "results/tables/; compare with results/numbers_reference.json)",
        "files": {str(p.relative_to(OUT)): sha256(p) for p in sorted(OUT.rglob("*")) if p.is_file()},
    }
    (OUT / "MANIFEST.json").write_text(json.dumps(manifest, indent=2))
    print(f"Staged release in {OUT}  ({sum(p.stat().st_size for p in OUT.rglob('*') if p.is_file()) / 1e6:.1f} MB)")


if __name__ == "__main__":
    main()