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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
from torch.distributions import Bernoulli
|
| 9 |
+
from joblib import Parallel, delayed
|
| 10 |
+
from matplotlib import pyplot as plt
|
| 11 |
+
from tqdm import tqdm
|
| 12 |
+
from tueplots import bundles
|
| 13 |
+
|
| 14 |
+
bundles.icml2024()
|
| 15 |
+
|
| 16 |
+
PROJECT_ROOT = Path(__file__).resolve().parent
|
| 17 |
+
sys.path.append(str(PROJECT_ROOT.parent))
|
| 18 |
+
from utils import (
|
| 19 |
+
cat_beta_1pl,
|
| 20 |
+
cat_beta_2pl,
|
| 21 |
+
cat_binary_1pl,
|
| 22 |
+
cat_binary_2pl,
|
| 23 |
+
beta_nll,
|
| 24 |
+
calibrate_1pl_theta,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
MAX_BUDGET = 100
|
| 28 |
+
N_TEST_MODELS = 5
|
| 29 |
+
RNG_SEED = 0
|
| 30 |
+
DATA_ROOT = PROJECT_ROOT / "data"
|
| 31 |
+
RESULTS_ROOT = PROJECT_ROOT / "results"
|
| 32 |
+
DEVICE = "cpu"
|
| 33 |
+
LOAD_PLOT_DATA = False
|
| 34 |
+
INIT_FRAC = 0
|
| 35 |
+
ONLY_PLOT_BETA_1PL = True
|
| 36 |
+
PLOT_METRIC = "mae"
|
| 37 |
+
NROWS = 2
|
| 38 |
+
NCOLS = 5
|
| 39 |
+
|
| 40 |
+
CONFIGS = (
|
| 41 |
+
{
|
| 42 |
+
"label": "beta 1pl",
|
| 43 |
+
"loss_kind": "beta",
|
| 44 |
+
"irt_model": "1pl",
|
| 45 |
+
"input_file": "4_prob_matrix_calibrated.parquet",
|
| 46 |
+
"color": "#1f77b4",
|
| 47 |
+
"linestyle": "-",
|
| 48 |
+
"cat_fn": cat_beta_1pl,
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"label": "beta 2pl",
|
| 52 |
+
"loss_kind": "beta",
|
| 53 |
+
"irt_model": "2pl",
|
| 54 |
+
"input_file": "4_prob_matrix_calibrated_2pl.parquet",
|
| 55 |
+
"color": "#1f77b4",
|
| 56 |
+
"linestyle": "--",
|
| 57 |
+
"cat_fn": cat_beta_2pl,
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"label": "binary 1pl",
|
| 61 |
+
"loss_kind": "binary",
|
| 62 |
+
"irt_model": "1pl",
|
| 63 |
+
"input_file": "4_binary_matrix_calibrated.parquet",
|
| 64 |
+
"color": "#d62728",
|
| 65 |
+
"linestyle": "-",
|
| 66 |
+
"cat_fn": cat_binary_1pl,
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"label": "binary 2pl",
|
| 70 |
+
"loss_kind": "binary",
|
| 71 |
+
"irt_model": "2pl",
|
| 72 |
+
"input_file": "4_binary_matrix_calibrated_2pl.parquet",
|
| 73 |
+
"color": "#d62728",
|
| 74 |
+
"linestyle": "--",
|
| 75 |
+
"cat_fn": cat_binary_2pl,
|
| 76 |
+
},
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def cat_theta_trace(
|
| 81 |
+
ys: np.ndarray,
|
| 82 |
+
zs: np.ndarray,
|
| 83 |
+
cat_fn,
|
| 84 |
+
device: str,
|
| 85 |
+
max_budget: int,
|
| 86 |
+
init_frac: float,
|
| 87 |
+
discris: np.ndarray | None = None,
|
| 88 |
+
) -> np.ndarray:
|
| 89 |
+
ys_t = torch.tensor(ys, dtype=torch.float32)
|
| 90 |
+
zs_t = torch.tensor(zs, dtype=torch.float32)
|
| 91 |
+
if discris is None:
|
| 92 |
+
raw_trace = np.asarray(
|
| 93 |
+
cat_fn(ys_t, zs_t, device, budget=max_budget, init_frac=init_frac),
|
| 94 |
+
dtype=np.float32,
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
discris_t = torch.tensor(discris, dtype=torch.float32)
|
| 98 |
+
raw_trace = np.asarray(
|
| 99 |
+
cat_fn(ys_t, discris_t, zs_t, device, budget=max_budget, init_frac=init_frac),
|
| 100 |
+
dtype=np.float32,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return raw_trace
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def calibrate_2pl_theta(
|
| 107 |
+
resmat: torch.Tensor,
|
| 108 |
+
zs: torch.Tensor,
|
| 109 |
+
alphas: torch.Tensor,
|
| 110 |
+
device: str,
|
| 111 |
+
loss_kind: str,
|
| 112 |
+
max_iter: int = 100,
|
| 113 |
+
lr_theta: float = 0.1,
|
| 114 |
+
phi: float = 10.0,
|
| 115 |
+
clamp_eps: float = 1e-6,
|
| 116 |
+
) -> np.ndarray:
|
| 117 |
+
resmat = resmat.to(device)
|
| 118 |
+
zs = zs.to(device)
|
| 119 |
+
alphas = alphas.to(device)
|
| 120 |
+
n_test_takers = resmat.shape[0]
|
| 121 |
+
thetas = torch.randn(n_test_takers, device=device, requires_grad=True)
|
| 122 |
+
optimizer = torch.optim.AdamW([thetas], lr=lr_theta)
|
| 123 |
+
phi_tensor = torch.tensor(phi, device=device)
|
| 124 |
+
|
| 125 |
+
if loss_kind == "beta":
|
| 126 |
+
def compute_loss(y, mu, mask):
|
| 127 |
+
y = y.clamp(clamp_eps, 1 - clamp_eps)
|
| 128 |
+
return beta_nll(y[mask], mu[mask], phi_tensor).mean()
|
| 129 |
+
elif loss_kind == "binary":
|
| 130 |
+
def compute_loss(y, mu, mask):
|
| 131 |
+
return -Bernoulli(probs=mu[mask]).log_prob(y[mask]).mean()
|
| 132 |
+
else:
|
| 133 |
+
raise ValueError(f"Unknown loss_kind: {loss_kind}")
|
| 134 |
+
|
| 135 |
+
for _ in range(max_iter):
|
| 136 |
+
optimizer.zero_grad()
|
| 137 |
+
mask = ~torch.isnan(resmat)
|
| 138 |
+
mu = torch.sigmoid(alphas[None, :] * (thetas[:, None] + zs[None, :]))
|
| 139 |
+
loss = compute_loss(resmat, mu, mask)
|
| 140 |
+
loss.backward()
|
| 141 |
+
optimizer.step()
|
| 142 |
+
|
| 143 |
+
thetas = thetas.detach()
|
| 144 |
+
return thetas.cpu().numpy()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def estimate_full_theta(
|
| 148 |
+
ys: np.ndarray,
|
| 149 |
+
zs: np.ndarray,
|
| 150 |
+
loss_kind: str,
|
| 151 |
+
irt_model: str,
|
| 152 |
+
device: str,
|
| 153 |
+
alphas: np.ndarray | None = None,
|
| 154 |
+
) -> np.ndarray:
|
| 155 |
+
ys_t = torch.tensor(ys, dtype=torch.float32)
|
| 156 |
+
zs_t = torch.tensor(zs, dtype=torch.float32)
|
| 157 |
+
if irt_model == "1pl":
|
| 158 |
+
return calibrate_1pl_theta(
|
| 159 |
+
resmat=ys_t,
|
| 160 |
+
device=device,
|
| 161 |
+
zs=zs_t,
|
| 162 |
+
loss_kind=loss_kind,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
else:
|
| 166 |
+
return calibrate_2pl_theta(
|
| 167 |
+
resmat=ys_t,
|
| 168 |
+
zs=zs_t,
|
| 169 |
+
alphas=torch.tensor(alphas, dtype=torch.float32),
|
| 170 |
+
device=device,
|
| 171 |
+
loss_kind=loss_kind,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if __name__ == "__main__":
|
| 175 |
+
n_cpus = int(os.cpu_count() * 0.8)
|
| 176 |
+
rng = np.random.default_rng(RNG_SEED)
|
| 177 |
+
results_dir = RESULTS_ROOT / "cat_budget_ablation"
|
| 178 |
+
results_dir.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
csv_path = results_dir / "cat_budget_ablation_mae.csv"
|
| 180 |
+
|
| 181 |
+
if LOAD_PLOT_DATA:
|
| 182 |
+
results_df = pd.read_csv(csv_path)
|
| 183 |
+
shared_benches = sorted(results_df["bench_name"].unique().tolist())
|
| 184 |
+
else:
|
| 185 |
+
config_data = {}
|
| 186 |
+
shared_benches = None
|
| 187 |
+
for cfg_idx, cfg in enumerate(CONFIGS):
|
| 188 |
+
df = pd.read_parquet(DATA_ROOT / cfg["input_file"])
|
| 189 |
+
test_df = df[df.index.get_level_values("model_split") == "test"].copy()
|
| 190 |
+
|
| 191 |
+
if cfg_idx == 0:
|
| 192 |
+
shared_benches = sorted(
|
| 193 |
+
test_df.columns.get_level_values("bench_name").map(
|
| 194 |
+
lambda b: "mmlu" if b.startswith("mmlu") else b
|
| 195 |
+
).unique().tolist()
|
| 196 |
+
)
|
| 197 |
+
config_data[cfg["label"]] = {
|
| 198 |
+
"test_df": test_df,
|
| 199 |
+
"bench_names": test_df.columns.get_level_values("bench_name").map(
|
| 200 |
+
lambda b: "mmlu" if b.startswith("mmlu") else b
|
| 201 |
+
).to_numpy(),
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
records = []
|
| 205 |
+
for cfg in CONFIGS:
|
| 206 |
+
label = cfg["label"]
|
| 207 |
+
test_df = config_data[label]["test_df"]
|
| 208 |
+
ys = test_df.to_numpy(dtype=np.float32)
|
| 209 |
+
bench_names = config_data[label]["bench_names"]
|
| 210 |
+
zs = test_df.columns.get_level_values("difficulty").to_numpy(dtype=np.float32)
|
| 211 |
+
if cfg["irt_model"] == "2pl":
|
| 212 |
+
alphas = test_df.columns.get_level_values("discrimination").to_numpy(dtype=np.float32)
|
| 213 |
+
else:
|
| 214 |
+
alphas = None
|
| 215 |
+
|
| 216 |
+
for bench in tqdm(shared_benches, desc=label):
|
| 217 |
+
bench_mask = bench_names == bench
|
| 218 |
+
bench_ys = ys[:, bench_mask]
|
| 219 |
+
bench_zs = zs[bench_mask]
|
| 220 |
+
bench_alphas = alphas[bench_mask] if alphas is not None else None
|
| 221 |
+
|
| 222 |
+
gt_thetas = estimate_full_theta(
|
| 223 |
+
ys=bench_ys,
|
| 224 |
+
zs=bench_zs,
|
| 225 |
+
loss_kind=cfg["loss_kind"],
|
| 226 |
+
irt_model=cfg["irt_model"],
|
| 227 |
+
alphas=bench_alphas,
|
| 228 |
+
device=DEVICE,
|
| 229 |
+
)
|
| 230 |
+
theta_order = np.argsort(gt_thetas)
|
| 231 |
+
n_select = min(N_TEST_MODELS, theta_order.size)
|
| 232 |
+
selected_positions = np.linspace(0, theta_order.size - 1, num=n_select, dtype=int)
|
| 233 |
+
selected_model_idxs = theta_order[selected_positions]
|
| 234 |
+
bench_ys = bench_ys[selected_model_idxs]
|
| 235 |
+
gt_thetas = gt_thetas[selected_model_idxs]
|
| 236 |
+
|
| 237 |
+
traces = np.asarray(
|
| 238 |
+
Parallel(n_jobs=n_cpus)(
|
| 239 |
+
delayed(cat_theta_trace)(
|
| 240 |
+
ys=bench_ys[i],
|
| 241 |
+
zs=bench_zs,
|
| 242 |
+
discris=bench_alphas,
|
| 243 |
+
cat_fn=cfg["cat_fn"],
|
| 244 |
+
device=DEVICE,
|
| 245 |
+
max_budget=MAX_BUDGET,
|
| 246 |
+
init_frac=INIT_FRAC,
|
| 247 |
+
)
|
| 248 |
+
for i in range(bench_ys.shape[0])
|
| 249 |
+
),
|
| 250 |
+
dtype=np.float32,
|
| 251 |
+
)
|
| 252 |
+
errors = traces - gt_thetas[:, None]
|
| 253 |
+
mae_by_budget = np.abs(errors).mean(axis=0)
|
| 254 |
+
mse_by_budget = np.square(errors).mean(axis=0)
|
| 255 |
+
|
| 256 |
+
for budget, (mae, mse) in enumerate(zip(mae_by_budget, mse_by_budget), start=1):
|
| 257 |
+
records.append(
|
| 258 |
+
{
|
| 259 |
+
"bench_name": bench,
|
| 260 |
+
"loss_kind": cfg["loss_kind"],
|
| 261 |
+
"irt_model": cfg["irt_model"],
|
| 262 |
+
"budget": budget,
|
| 263 |
+
"mae": float(mae),
|
| 264 |
+
"mse": float(mse),
|
| 265 |
+
}
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
results_df = pd.DataFrame.from_records(records)
|
| 269 |
+
results_df.to_csv(csv_path, index=False)
|
| 270 |
+
|
| 271 |
+
with plt.rc_context(bundles.icml2024(usetex=True, family="serif")):
|
| 272 |
+
fig, axes = plt.subplots(
|
| 273 |
+
nrows=NROWS,
|
| 274 |
+
ncols=NCOLS,
|
| 275 |
+
figsize=(18, 6.8),
|
| 276 |
+
sharex=True,
|
| 277 |
+
sharey=False,
|
| 278 |
+
)
|
| 279 |
+
axes = np.atleast_1d(axes).ravel()
|
| 280 |
+
plot_configs = (
|
| 281 |
+
[cfg for cfg in CONFIGS if cfg["loss_kind"] == "beta" and cfg["irt_model"] == "1pl"]
|
| 282 |
+
if ONLY_PLOT_BETA_1PL
|
| 283 |
+
else list(CONFIGS)
|
| 284 |
+
)
|
| 285 |
+
for i_ax, (ax, bench) in enumerate(zip(axes, shared_benches)):
|
| 286 |
+
bench_df = results_df[results_df["bench_name"] == bench]
|
| 287 |
+
for cfg in plot_configs:
|
| 288 |
+
cfg_df = bench_df[
|
| 289 |
+
(bench_df["loss_kind"] == cfg["loss_kind"])
|
| 290 |
+
& (bench_df["irt_model"] == cfg["irt_model"])
|
| 291 |
+
]
|
| 292 |
+
ax.plot(
|
| 293 |
+
cfg_df["budget"],
|
| 294 |
+
cfg_df[PLOT_METRIC],
|
| 295 |
+
label=None if ONLY_PLOT_BETA_1PL else cfg["label"],
|
| 296 |
+
color=cfg["color"],
|
| 297 |
+
linestyle=cfg["linestyle"],
|
| 298 |
+
linewidth=2.4,
|
| 299 |
+
alpha=0.8,
|
| 300 |
+
)
|
| 301 |
+
plot_df = bench_df[
|
| 302 |
+
(bench_df["loss_kind"] == "beta") & (bench_df["irt_model"] == "1pl")
|
| 303 |
+
] if ONLY_PLOT_BETA_1PL else bench_df
|
| 304 |
+
if ONLY_PLOT_BETA_1PL:
|
| 305 |
+
bench_max = plot_df[PLOT_METRIC].max()
|
| 306 |
+
ax.set_ylim(0, bench_max * 1.12 if bench_max > 0 else 1.0)
|
| 307 |
+
else:
|
| 308 |
+
positive_metric = plot_df.loc[plot_df[PLOT_METRIC] > 0, PLOT_METRIC]
|
| 309 |
+
bench_min = positive_metric.min()
|
| 310 |
+
bench_max = positive_metric.max()
|
| 311 |
+
ax.set_yscale("log")
|
| 312 |
+
ax.set_ylim(bench_min / 1.2, bench_max * 1.12)
|
| 313 |
+
ax.set_xlim(1, MAX_BUDGET)
|
| 314 |
+
ax.axvline(50, color="black", linestyle="--", linewidth=1.2, alpha=0.9)
|
| 315 |
+
ax.set_title(bench, fontsize=18, pad=10)
|
| 316 |
+
if i_ax < NCOLS:
|
| 317 |
+
ax.set_xlabel("")
|
| 318 |
+
else:
|
| 319 |
+
ax.set_xlabel("Budget", fontsize=16)
|
| 320 |
+
if i_ax % NCOLS == 0:
|
| 321 |
+
ax.set_ylabel(PLOT_METRIC.upper(), fontsize=16)
|
| 322 |
+
else:
|
| 323 |
+
ax.set_ylabel("")
|
| 324 |
+
ax.tick_params(axis="both", labelsize=14)
|
| 325 |
+
ax.spines["top"].set_visible(False)
|
| 326 |
+
ax.spines["right"].set_visible(False)
|
| 327 |
+
ax.margins(x=0.01)
|
| 328 |
+
if not ONLY_PLOT_BETA_1PL:
|
| 329 |
+
handles, labels = axes[0].get_legend_handles_labels()
|
| 330 |
+
fig.legend(
|
| 331 |
+
handles,
|
| 332 |
+
labels,
|
| 333 |
+
loc="upper center",
|
| 334 |
+
ncol=4,
|
| 335 |
+
frameon=False,
|
| 336 |
+
fontsize=15,
|
| 337 |
+
bbox_to_anchor=(0.5, 1.03),
|
| 338 |
+
)
|
| 339 |
+
fig.tight_layout(rect=(0, 0, 1, 0.92), w_pad=1.2, h_pad=1.4)
|
| 340 |
+
fig.savefig(results_dir / "cat_budget_ablation.png", dpi=300, bbox_inches="tight")
|
| 341 |
+
plt.close(fig)
|