| """Benchmark LPRMono vs GREEDY on CIFAR-10 embedding instances (arXiv 2508.16007v2, Fig. 1). | |
| Instance generator, LP (Eq. 3), LPR, LPRMono (data burning) and GREEDY per the paper's | |
| Sec. 5 / Example 1. Vectorized LP construction and E[C] (sparse matvec) for large n. | |
| Timing protocol: wall-clock around (neighborhood construction) and around each algorithm's | |
| allocation step (LP solve + rounding + burning | greedy loop). Payments excluded. | |
| Usage: | |
| python benchmark.py --emb-path /data/cifar10_embeddings.npz --n 5000 --instances 2 \ | |
| --seed 0 --out /data/results_n5000.jsonl [--skip-naive] | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| import time | |
| import numpy as np | |
| import scipy.sparse as sp | |
| from scipy.optimize import linprog | |
| M = 3 | |
| LAM = np.arange(10) / 10.0 | |
| def load_embeddings(path): | |
| data = np.load(path) | |
| x = np.asarray(data["x_train"], dtype=np.float32) | |
| y = np.asarray(data["y_train"]) | |
| if y.ndim == 2: | |
| y = y.argmax(axis=1) | |
| y = y.astype(np.int64).ravel() | |
| assert x.shape == (50000, 2048), f"unexpected embedding shape {x.shape}" | |
| assert y.shape == (50000,) | |
| return x, y | |
| def class_ref_distances(x, y, num_classes=10, k=100, seed=0): | |
| rng = np.random.default_rng(seed) | |
| R = np.zeros(num_classes, dtype=np.float64) | |
| for c in range(num_classes): | |
| idx = np.where(y == c)[0] | |
| s = rng.choice(idx, size=min(k, len(idx)), replace=False) | |
| P = x[s].astype(np.float64) | |
| sq = (P * P).sum(1) | |
| d2 = sq[:, None] + sq[None, :] - 2.0 * (P @ P.T) | |
| np.maximum(d2, 0.0, out=d2) | |
| R[c] = np.sqrt(d2)[np.triu_indices(len(s), 1)].mean() | |
| return R | |
| def make_instance(x, y, R, n, rng): | |
| idx = rng.choice(len(x), size=n, replace=False) | |
| X = x[idx] | |
| cls = y[idx] | |
| theta = LAM[rng.integers(0, len(LAM), size=M)].astype(np.float64) | |
| alpha = rng.random(M) | |
| w_class = rng.random((M, R.size)) | |
| w = w_class[:, cls] | |
| w = w / w.sum(axis=1, keepdims=True) | |
| radii = alpha[:, None] * R[cls][None, :] | |
| return X, cls, theta, alpha, w, radii | |
| def neighborhoods(X, radii): | |
| """Per-buyer CSR masks N_i(j). Distances via float32 Gram to keep n=20000 in memory.""" | |
| G = (X @ X.T).astype(np.float32) | |
| sq = (X.astype(np.float64) * X).sum(1).astype(np.float32) | |
| d2 = sq[:, None] + sq[None, :] - 2.0 * G | |
| np.maximum(d2, 0.0, out=d2) | |
| del G | |
| nbrs = [] | |
| for i in range(M): | |
| mask = d2 <= (radii[i].astype(np.float32) ** 2)[:, None] | |
| nbrs.append(sp.csr_matrix(mask)) | |
| del d2, mask | |
| return nbrs | |
| def build_lp(nbrs, theta, w, n): | |
| """Vectorized sparse assembly of LP (Eq. 3). Variables [X (m*n), C (m*n)].""" | |
| all_rows, all_cols, all_vals = [], [], [] | |
| n_cov = M * n | |
| for i in range(M): | |
| N = nbrs[i] | |
| counts = np.diff(N.indptr) | |
| rows_j = i * n + np.repeat(np.arange(n), counts) # global row block for buyer i | |
| all_rows.append(rows_j) | |
| all_cols.append(i * n + N.indices) # X[i, j'] block | |
| all_vals.append(np.full(rows_j.size, -1.0)) | |
| # C coefficients in coverage rows: row (i*n+j) -> C var M*n + i*n+j | |
| cov_rows = np.arange(n_cov) | |
| all_rows.append(cov_rows) | |
| all_cols.append(M * n + cov_rows) | |
| all_vals.append(np.ones(n_cov)) | |
| # exclusion rows: sum_i X_ij <= 1; for point j the entries are X[i*n+j] for i=0..M-1 | |
| ex_rows = np.repeat(n_cov + np.arange(n), M) | |
| ex_cols = np.tile(np.arange(M), n) * n + np.repeat(np.arange(n), M) # [0*n+j, 1*n+j, 2*n+j] per j | |
| ex_vals = np.ones(M * n) | |
| all_rows.append(ex_rows) | |
| all_cols.append(ex_cols) | |
| all_vals.append(ex_vals) | |
| rows = np.concatenate(all_rows).astype(np.int32) | |
| cols = np.concatenate(all_cols).astype(np.int32) | |
| vals = np.concatenate(all_vals) | |
| A_ub = sp.coo_matrix((vals, (rows, cols)), shape=(n_cov + n, 2 * M * n)).tocsr() | |
| b_ub = np.concatenate([np.zeros(n_cov), np.ones(n)]) | |
| c = np.concatenate([np.zeros(M * n), -np.concatenate([theta[i] * w[i] for i in range(M)])]) | |
| return A_ub, b_ub, c | |
| LP_METHOD = "highs-ipm" # interior point: dual simplex ('highs') did not converge in >17 min | |
| # on set-covering LPs with 4M+ nonzeros; ipm solves n=5000 in ~36 s | |
| def solve_lp(nbrs, theta, w, n, timer=None): | |
| t0 = time.perf_counter() | |
| A_ub, b_ub, c = build_lp(nbrs, theta, w, n) | |
| t_build = time.perf_counter() - t0 | |
| t0 = time.perf_counter() | |
| res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=(0, 1), method=LP_METHOD) | |
| t_solve = time.perf_counter() - t0 | |
| assert res.success, f"LP failed: {res.message}" | |
| if timer is not None: | |
| timer.update(lp_build=t_build, lp_solve=t_solve) | |
| return res.x[: M * n].reshape(M, n), res.x[M * n:].reshape(M, n), res | |
| def lp_objective(Xbar, Cbar, theta, w): | |
| return sum(theta[i] * (w[i] * Cbar[i]).sum() for i in range(M)) | |
| def expected_coverage(Xbar, nbrs, w, n): | |
| """E[C_i] = sum_j w_ij (1 - prod_{j' in N_i(j)} (1 - Xbar_ij')), via sparse matvec.""" | |
| EC = np.zeros(M) | |
| for i in range(M): | |
| log_keep = np.log(np.clip(1.0 - Xbar[i], 1e-300, 1.0)) | |
| row_sums = nbrs[i] @ log_keep # sum over N_i(j) | |
| EC[i] = (w[i] * (1.0 - np.exp(row_sums))).sum() | |
| return EC | |
| def round_allocation(Xbar, rng): | |
| cum = Xbar.cumsum(axis=0) | |
| u = rng.random(Xbar.shape[1]) | |
| return (cum < u[None, :]).sum(axis=0) | |
| def coverage_from_alloc(alloc, nbrs, n): | |
| cov = [] | |
| for i in range(M): | |
| idx = np.where(alloc == i)[0] | |
| vec = np.zeros(n) | |
| vec[idx] = 1.0 | |
| covered = (nbrs[i] @ vec) > 0 # sparse @ dense 1-D -> dense (n,) | |
| cov.append(covered.astype(np.float64)) | |
| return cov | |
| def welfare(alloc, cov, theta, w): | |
| return sum(theta[i] * (w[i] * cov[i]).sum() for i in range(M)) | |
| def lpr(nbrs, theta, w, n, rng, timer=None): | |
| timer = timer or {} | |
| Xbar, Cbar, _ = solve_lp(nbrs, theta, w, n, timer) | |
| t0 = time.perf_counter() | |
| alloc = round_allocation(Xbar, rng) | |
| EC = expected_coverage(Xbar, nbrs, w, n) | |
| cov = coverage_from_alloc(alloc, nbrs, n) | |
| timer["round"] = time.perf_counter() - t0 | |
| obj = lp_objective(Xbar, Cbar, theta, w) | |
| exp_welfare = sum(theta[i] * EC[i] for i in range(M)) | |
| return dict(alloc=alloc, cov=cov, obj=obj, realized=welfare(alloc, cov, theta, w), | |
| expected=exp_welfare, timer=timer) | |
| def lprmono(nbrs, theta, w, n, rng, timer=None): | |
| timer = timer or {} | |
| Xbar, Cbar, _ = solve_lp(nbrs, theta, w, n, timer) | |
| t0 = time.perf_counter() | |
| alloc = round_allocation(Xbar, rng) | |
| EC = expected_coverage(Xbar, nbrs, w, n) | |
| Cbar_i = np.array([(w[i] * Cbar[i]).sum() for i in range(M)]) | |
| rho = np.where(Cbar_i > 0, (1 - 1 / np.e) * Cbar_i / np.maximum(EC, 1e-300), 0.0) | |
| rho = np.minimum(rho, 1.0) | |
| keep = rng.random(M) < rho | |
| for i in range(M): | |
| if not keep[i]: | |
| alloc[alloc == i] = M | |
| timer["round_burn"] = time.perf_counter() - t0 | |
| obj = lp_objective(Xbar, Cbar, theta, w) | |
| exp_welfare = sum(theta[i] * rho[i] * EC[i] for i in range(M)) | |
| return dict(alloc=alloc, obj=obj, expected=exp_welfare, rho=rho, EC=EC, timer=timer) | |
| def greedy(nbrs, theta, w, n, rng=None): | |
| """GREEDY per Example 1 with precomputed neighborhoods: per point, allocate to the | |
| buyer with max bid-weighted marginal coverage gain. | |
| Coverage orientation (paper Sec. 2): point x is covered iff d(x, j') <= r_ix for some | |
| allocated j' -- the radius belongs to the COVERED point. So allocating point j covers | |
| the points in COLUMN j of the neighborhood mask (= row j of its transpose); gains and | |
| updates both use the transposed masks.""" | |
| t0 = time.perf_counter() | |
| u = [np.ones(n, dtype=bool) for _ in range(M)] | |
| alloc = np.full(n, M, dtype=np.int64) | |
| Nt = [nbrs[i].T.tocsr() for i in range(M)] # row j of Nt = points covered by allocating j | |
| for j in range(n): | |
| gains = np.empty(M) | |
| for i in range(M): | |
| N = Nt[i] | |
| nidx = N.indices[N.indptr[j]:N.indptr[j + 1]] | |
| gains[i] = theta[i] * float(np.dot(w[i][nidx], u[i][nidx])) if nidx.size else 0.0 | |
| best = int(np.argmax(gains)) | |
| if gains[best] > 0: | |
| alloc[j] = best | |
| N = Nt[best] | |
| u[best][N.indices[N.indptr[j]:N.indptr[j + 1]]] = False | |
| cov = [1.0 - u[i].astype(np.float64) for i in range(M)] | |
| t_g = time.perf_counter() - t0 | |
| welfare_g = sum(theta[i] * (w[i] * cov[i]).sum() for i in range(M)) | |
| return alloc, welfare_g, t_g | |
| def greedy_pairwise(X, radii, theta, w, n): | |
| """Naive GREEDY as the paper's absolute runtimes suggest: no precomputed neighborhoods; | |
| for each (point, buyer) recompute distances to all points on the fly.""" | |
| t0 = time.perf_counter() | |
| u = [np.ones(n, dtype=bool) for _ in range(M)] | |
| alloc = np.full(n, M, dtype=np.int64) | |
| Xd = X.astype(np.float64) | |
| for j in range(n): | |
| d2 = ((Xd - Xd[j]) ** 2).sum(1) # d2[x] = d(x, j)^2, rows indexed by covered point x | |
| gains = np.empty(M) | |
| for i in range(M): | |
| within = d2 <= radii[i] ** 2 # per-covered-point radius r_ix (column semantics) | |
| gains[i] = theta[i] * float((w[i] * within * u[i]).sum()) | |
| best = int(np.argmax(gains)) | |
| if gains[best] > 0: | |
| alloc[j] = best | |
| u[best][d2 <= radii[best] ** 2] = False | |
| cov = [1.0 - u[i].astype(np.float64) for i in range(M)] | |
| t_g = time.perf_counter() - t0 | |
| welfare_g = sum(theta[i] * (w[i] * cov[i]).sum() for i in range(M)) | |
| return alloc, welfare_g, t_g | |
| def run_instance(x, y, R, n, seed, skip_naive=False, skip_pairwise=False): | |
| rng = np.random.default_rng(seed) | |
| X, cls, theta, alpha, w, radii = make_instance(x, y, R, n, rng) | |
| t0 = time.perf_counter() | |
| nbrs = neighborhoods(X, radii) | |
| t_nbr = time.perf_counter() - t0 | |
| rec = dict(n=n, seed=seed, theta=theta.tolist(), alpha=alpha.tolist(), | |
| t_neighborhoods=t_nbr, | |
| avg_nbr_size=[float(nbrs[i].nnz) / n for i in range(M)], | |
| nbr_nnz=[int(nbrs[i].nnz) for i in range(M)]) | |
| mono = lprmono(nbrs, theta, w, n, np.random.default_rng(seed + 13)) | |
| print(f"[inst {seed}] n={n} mono done: lp_build={mono['timer']['lp_build']:.2f} lp_solve={mono['timer']['lp_solve']:.2f} round_burn={mono['timer']['round_burn']:.2f} nbr={t_nbr:.2f}", file=sys.stderr, flush=True) | |
| rec["lprmono"] = dict(expected=mono["expected"], obj=mono["obj"], rho=mono["rho"].tolist(), | |
| timer=mono["timer"]) | |
| l = lpr(nbrs, theta, w, n, np.random.default_rng(seed + 7)) | |
| print(f"[inst {seed}] lpr done: lp_solve={l['timer']['lp_solve']:.2f} round={l['timer']['round']:.2f}", file=sys.stderr, flush=True) | |
| rec["lpr"] = dict(expected=l["expected"], realized=l["realized"], obj=l["obj"], timer=l["timer"]) | |
| alloc_g, welfare_g, t_g = greedy(nbrs, theta, w, n) | |
| print(f"[inst {seed}] greedy(precomputed-nbrs) done: {t_g:.2f}s", file=sys.stderr, flush=True) | |
| rec["greedy"] = dict(welfare=welfare_g, t=t_g) | |
| if not skip_pairwise: | |
| print(f"[inst {seed}] starting greedy_pairwise (naive, slow)...", file=sys.stderr, flush=True) | |
| alloc_p, welfare_p, t_p = greedy_pairwise(X, radii, theta, w, n) | |
| print(f"[inst {seed}] greedy_pairwise done: {t_p:.2f}s", file=sys.stderr, flush=True) | |
| rec["greedy_pairwise"] = dict(welfare=welfare_p, t=t_p) | |
| # LP (Eq. 3) is a relaxation: its optimum must dominate every feasible allocation, | |
| # including both greedy variants. Catches constraint-assembly bugs cheaply. | |
| assert rec["greedy"]["welfare"] <= rec["lpr"]["obj"] + 1e-6, \ | |
| f"LP {rec['lpr']['obj']} < greedy {rec['greedy']['welfare']} — LP not a relaxation, aborting" | |
| if "greedy_pairwise" in rec: | |
| assert rec["greedy_pairwise"]["welfare"] <= rec["lpr"]["obj"] + 1e-6, \ | |
| f"LP {rec['lpr']['obj']} < pairwise greedy {rec['greedy_pairwise']['welfare']}" | |
| rec["lprmono_ratio"] = rec["lprmono"]["expected"] / rec["lprmono"]["obj"] | |
| rec["lpr_exp_ratio"] = rec["lpr"]["expected"] / rec["lpr"]["obj"] | |
| rec["greedy_ratio"] = rec["greedy"]["welfare"] / rec["lpr"]["obj"] | |
| print(json.dumps(rec), flush=True) | |
| return rec | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--emb-path", default="/data/cifar10_embeddings.npz") | |
| ap.add_argument("--n", type=int, required=True) | |
| ap.add_argument("--instances", type=int, default=1) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--out", default=None) | |
| ap.add_argument("--skip-pairwise", action="store_true") | |
| args = ap.parse_args() | |
| t0 = time.perf_counter() | |
| x, y = load_embeddings(args.emb_path) | |
| print(f"[load] {x.shape} {time.perf_counter()-t0:.1f}s", flush=True) | |
| R = class_ref_distances(x, y, seed=args.seed) | |
| out = open(args.out, "a") if args.out else None | |
| for inst in range(args.instances): | |
| seed = args.seed * 1000 + inst | |
| rec = run_instance(x, y, R, args.n, seed, skip_pairwise=args.skip_pairwise) | |
| if out: | |
| out.write(json.dumps(rec) + "\n") | |
| out.flush() | |
| if out: | |
| out.close() | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 13.1 kB
- Xet hash:
- a652b6d47b9a98cd00c612a5375c8e8746048a47eaf8d3f52c63752f9d2edf13
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.