Upload benchmark_job.py
Browse files- benchmark_job.py +401 -4
benchmark_job.py
CHANGED
|
@@ -1,11 +1,30 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
RTB Bidding Algorithms Benchmark β First-Price Auctions
|
|
|
|
| 4 |
Self-contained script for HF Jobs execution.
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
Usage:
|
| 8 |
python benchmark_job.py --max_rows 200000 --budget 10000 --T 10000 --n_runs 5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
import os, json, time, argparse
|
| 11 |
import numpy as np
|
|
@@ -16,6 +35,384 @@ from sklearn.model_selection import train_test_split
|
|
| 16 |
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
| 17 |
from sklearn.metrics import roc_auc_score
|
| 18 |
|
| 19 |
-
|
| 20 |
-
#
|
| 21 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
RTB Bidding Algorithms Benchmark β First-Price Auctions
|
| 4 |
+
=========================================================
|
| 5 |
Self-contained script for HF Jobs execution.
|
| 6 |
+
|
| 7 |
+
Includes all 6 algorithms with detailed docstrings explaining each algorithm:
|
| 8 |
+
- DualOGD β Lagrangian dual + online gradient descent (Wang et al. 2023)
|
| 9 |
+
- TwoSidedDual β Budget cap + spend floor (k% minimum)
|
| 10 |
+
- ValueShading β Adaptive value shading for first-price auctions
|
| 11 |
+
- RLB β MDP-based reinforcement learning (Cai et al. 2017)
|
| 12 |
+
- Linear β Proportional bidding baseline
|
| 13 |
+
- Threshold β Fixed-bid-if-pCTR-above-threshold baseline
|
| 14 |
+
|
| 15 |
+
See README.md for full algorithm descriptions and benchmark results.
|
| 16 |
+
See RESEARCH_RESOURCES.md for comprehensive literature survey.
|
| 17 |
+
|
| 18 |
+
Repo: https://huggingface.co/hamverbot/bidding_algorithms_benchmark
|
| 19 |
+
Primary Paper: Wang et al. 2023, arXiv:2304.13477
|
| 20 |
|
| 21 |
Usage:
|
| 22 |
python benchmark_job.py --max_rows 200000 --budget 10000 --T 10000 --n_runs 5
|
| 23 |
+
|
| 24 |
+
Data Note:
|
| 25 |
+
Criteo_x4 (reczoo/Criteo_x4) is 5.6GB across 37 Parquet files.
|
| 26 |
+
Streaming 200K rows takes ~7 minutes due to the sequential scan over many files.
|
| 27 |
+
For faster iterations, use --max_rows 20000 to load in ~45 seconds.
|
| 28 |
"""
|
| 29 |
import os, json, time, argparse
|
| 30 |
import numpy as np
|
|
|
|
| 35 |
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
| 36 |
from sklearn.metrics import roc_auc_score
|
| 37 |
|
| 38 |
+
|
| 39 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
# BIDDING ALGORITHMS
|
| 41 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
+
# Each algorithm has a detailed docstring explaining its mechanism.
|
| 43 |
+
# All are designed for FIRST-PRICE auctions (winner pays their bid).
|
| 44 |
+
# See README.md for the full theoretical treatment.
|
| 45 |
+
|
| 46 |
+
class DualOGDBidder:
|
| 47 |
+
"""
|
| 48 |
+
## DualOGD β Lagrangian Dual + Online Gradient Descent
|
| 49 |
+
|
| 50 |
+
**Paper**: Wang et al. (2023), arXiv:2304.13477
|
| 51 |
+
"Learning to Bid in Repeated First-Price Auctions with Budgets"
|
| 52 |
+
|
| 53 |
+
The canonical approach: cast budget-constrained bidding as Lagrangian
|
| 54 |
+
optimization. A dual multiplier Ξ» tracks over/under-spending relative to
|
| 55 |
+
target rate Ο = B/T.
|
| 56 |
+
|
| 57 |
+
**Bid rule**: b_t = argmax_b [(v-b)Β·GΜ(b) β λ·bΒ·GΜ(b)]
|
| 58 |
+
Maximizes (expected reward β Ξ» Γ expected cost)
|
| 59 |
+
|
| 60 |
+
**Update**: Ξ» β max(0, Ξ» β Ρ·(Ο β actual_cost))
|
| 61 |
+
- Overspent β Ξ» grows β future bids penalized more
|
| 62 |
+
- Underspent β Ξ» shrinks β future bids cheaper
|
| 63 |
+
|
| 64 |
+
**Regret bound**: Γ(βT) β provably near-optimal.
|
| 65 |
+
|
| 66 |
+
**Limitation**: Without a floor constraint, Ξ» becomes conservative early
|
| 67 |
+
and the algorithm leaves 20-25% of budget unspent. See TwoSidedDual.
|
| 68 |
+
"""
|
| 69 |
+
def __init__(self, budget, T, vpc, epsilon=None, name="DualOGD"):
|
| 70 |
+
self.B=budget; self.T=T; self.rho=budget/T; self.vpc=vpc; self.name=name
|
| 71 |
+
self.lambd=0.0; self.epsilon=epsilon or 1.0/np.sqrt(T)
|
| 72 |
+
self.total_spent=0.0; self.remaining_budget=budget
|
| 73 |
+
self.t=0; self.total_wins=0; self.competing_bids=[]
|
| 74 |
+
def bid(self, pctr, features=None):
|
| 75 |
+
self.t+=1
|
| 76 |
+
if self.remaining_budget<=0: return 0.0
|
| 77 |
+
v=pctr*self.vpc; mb=min(v*2.0,self.remaining_budget)
|
| 78 |
+
if mb<=0.1: return 0.0
|
| 79 |
+
return self._opt(v,mb)
|
| 80 |
+
def _opt(self,v,mb,n=50):
|
| 81 |
+
if not self.competing_bids: return v*0.5
|
| 82 |
+
bb,bs=0.0,-9e9
|
| 83 |
+
for b in np.linspace(0.1,mb,n):
|
| 84 |
+
wp=np.mean([1.0 if b>=d else 0.0 for d in self.competing_bids])
|
| 85 |
+
s=(v-b)*wp-self.lambd*b*wp
|
| 86 |
+
if s>bs: bs=s; bb=b
|
| 87 |
+
return float(bb)
|
| 88 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 89 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 90 |
+
if d_t: self.competing_bids.append(d_t)
|
| 91 |
+
cf=cost if won else 0.0
|
| 92 |
+
self.lambd=max(0.0, self.lambd-self.epsilon*(self.rho-cf))
|
| 93 |
+
def get_stats(self):
|
| 94 |
+
return {'name':self.name,'lambda':float(self.lambd),'spent':float(self.total_spent),
|
| 95 |
+
'remaining':float(self.remaining_budget),'budget_used':float(self.total_spent/self.B) if self.B>0 else 0,
|
| 96 |
+
'wins':self.total_wins,'t':self.t,'epsilon':float(self.epsilon),'rho':float(self.rho)}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class TwoSidedDualBidder(DualOGDBidder):
|
| 100 |
+
"""
|
| 101 |
+
## TwoSidedDual β Budget Cap + Spend Floor
|
| 102 |
+
|
| 103 |
+
Extension of DualOGD. Two dual variables for two constraints:
|
| 104 |
+
|
| 105 |
+
**ΞΌ (cap)**: ΞΌ β max(0, ΞΌ β Ξ·βΒ·(Ο β cost))
|
| 106 |
+
Penalizes overspending β restrains when ahead on spend.
|
| 107 |
+
|
| 108 |
+
**Ξ½ (floor)**: Ξ½ β max(0, Ξ½ β Ξ·βΒ·(cost β kΒ·Ο))
|
| 109 |
+
Penalizes UNDERspending β encourages when behind on floor.
|
| 110 |
+
|
| 111 |
+
**Effective multiplier**: (ΞΌ β Ξ½). When Ξ½ > ΞΌ, penalty becomes negative
|
| 112 |
+
β bidding is encouraged to hit the spend floor.
|
| 113 |
+
|
| 114 |
+
**Bid rule**: b_t = argmax_b [(vβb)Β·GΜ(b) β (ΞΌβΞ½)Β·bΒ·GΜ(b)]
|
| 115 |
+
|
| 116 |
+
This algorithm is the best-performing in our benchmark because it balances
|
| 117 |
+
the budget cap with a contractual minimum spend requirement (common in
|
| 118 |
+
brand advertising campaigns).
|
| 119 |
+
"""
|
| 120 |
+
def __init__(self,budget,T,vpc,k=0.8,ec=None,ef=None,name="TwoSidedDual"):
|
| 121 |
+
super().__init__(budget,T,vpc,ec,name)
|
| 122 |
+
self.k=k; self.k_rho=k*self.rho; self.nu=0.0
|
| 123 |
+
self.ef=ef or 1.0/np.sqrt(T); self.mu=self.lambd; self.ec=self.epsilon
|
| 124 |
+
def _opt(self,v,mb,n=50):
|
| 125 |
+
if not self.competing_bids: return v*0.5
|
| 126 |
+
eff=self.mu-self.nu; bb,bs=0.0,-9e9
|
| 127 |
+
for b in np.linspace(0.1,mb,n):
|
| 128 |
+
wp=np.mean([1.0 if b>=d else 0.0 for d in self.competing_bids])
|
| 129 |
+
s=(v-b)*wp-eff*b*wp
|
| 130 |
+
if s>bs: bs=s; bb=b
|
| 131 |
+
return float(bb)
|
| 132 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 133 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 134 |
+
if d_t: self.competing_bids.append(d_t)
|
| 135 |
+
cf=cost if won else 0.0
|
| 136 |
+
self.mu=max(0.0,self.mu-self.ec*(self.rho-cf))
|
| 137 |
+
self.nu=max(0.0,self.nu-self.ef*(cf-self.k_rho))
|
| 138 |
+
self.lambd=self.mu
|
| 139 |
+
def get_stats(self):
|
| 140 |
+
s=super().get_stats()
|
| 141 |
+
s.update({'mu':float(self.mu),'nu':float(self.nu),'k':float(self.k)})
|
| 142 |
+
return s
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ValueShadingBidder:
|
| 146 |
+
"""
|
| 147 |
+
## ValueShading β Adaptive Bid Shading for First-Price
|
| 148 |
+
|
| 149 |
+
In first-price auctions, bidding your true value guarantees zero surplus
|
| 150 |
+
(winner's curse). ValueShading scales bids: bid = v / (1 + Ξ»).
|
| 151 |
+
|
| 152 |
+
Ξ» adapts online: wins β Ξ» decreases (bid higher next time),
|
| 153 |
+
losses β Ξ» increases (bid more aggressively).
|
| 154 |
+
|
| 155 |
+
Faster than DualOGD (closed-form, no grid search) but less precise
|
| 156 |
+
about budget pacing. Spends full budget but with 16% higher CPC.
|
| 157 |
+
"""
|
| 158 |
+
def __init__(self,budget,T,vpc,name="ValueShading"):
|
| 159 |
+
self.B=budget; self.T=T; self.rho=budget/T; self.vpc=vpc; self.name=name
|
| 160 |
+
self.lambd=0.0; self.epsilon=1.0/np.sqrt(T)
|
| 161 |
+
self.total_spent=0.0; self.remaining_budget=budget
|
| 162 |
+
self.t=0; self.total_wins=0; self.competing_bids=[]
|
| 163 |
+
def bid(self,pctr,features=None):
|
| 164 |
+
self.t+=1; v=pctr*self.vpc
|
| 165 |
+
if self.remaining_budget<=0: return 0.0
|
| 166 |
+
if self.competing_bids:
|
| 167 |
+
bid=np.clip(v/(1.0+self.lambd+0.1),np.mean(self.competing_bids)*0.5,v*0.9)
|
| 168 |
+
else: bid=v*0.5
|
| 169 |
+
return min(bid,self.remaining_budget)
|
| 170 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 171 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 172 |
+
if d_t: self.competing_bids.append(d_t)
|
| 173 |
+
self.lambd=max(0.0,self.lambd-self.epsilon*(self.rho-(cost if won else 0.0)))
|
| 174 |
+
def get_stats(self):
|
| 175 |
+
return {'name':self.name,'lambda':float(self.lambd),'spent':float(self.total_spent),
|
| 176 |
+
'remaining':float(self.remaining_budget),'wins':self.total_wins,'t':self.t}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class RLBBidder:
|
| 180 |
+
"""
|
| 181 |
+
## RLB β Reinforcement Learning for Bidding
|
| 182 |
+
|
| 183 |
+
**Paper**: Cai et al. (2017), WSDM 2017, arXiv:1701.02490
|
| 184 |
+
"Real-Time Bidding by Reinforcement Learning in Display Advertising"
|
| 185 |
+
|
| 186 |
+
MDP formulation:
|
| 187 |
+
- State: (remaining_budget_ratio, pCTR_bucket)
|
| 188 |
+
- Action: bid_multiplier β {0.1Γ, 0.3Γ, ..., 2.0Γ} of value
|
| 189 |
+
- Reward: pCTR Γ value_per_click if won, else 0
|
| 190 |
+
|
| 191 |
+
Tabular Q-learning with Ξ΅-greedy exploration. No regret guarantees.
|
| 192 |
+
Needs many more auctions to converge than the optimization-based methods.
|
| 193 |
+
"""
|
| 194 |
+
def __init__(self,budget,T,vpc,name="RLB"):
|
| 195 |
+
self.B=budget; self.T=T; self.vpc=vpc; self.name=name
|
| 196 |
+
nb,np_,na=10,5,10
|
| 197 |
+
self.Q=np.zeros((nb,np_,na)); self.bm=np.linspace(0.1,2.0,na)
|
| 198 |
+
self.lr=0.1; self.gamma=0.95; self.eps=0.1
|
| 199 |
+
self.total_spent=0.0; self.remaining_budget=budget
|
| 200 |
+
self.t=0; self.total_wins=0; self.ls=None; self.la=None; self.nb=nb; self.np=np_
|
| 201 |
+
def _s(self,pctr):
|
| 202 |
+
br=self.remaining_budget/max(self.B,1)
|
| 203 |
+
return (min(int(br*self.nb),self.nb-1), min(int(pctr*self.np),self.np-1))
|
| 204 |
+
def bid(self,pctr,features=None):
|
| 205 |
+
self.t+=1
|
| 206 |
+
if self.remaining_budget<=0: return 0.0
|
| 207 |
+
s=self._s(pctr); v=pctr*self.vpc
|
| 208 |
+
a=np.random.randint(len(self.bm)) if np.random.random()<self.eps else np.argmax(self.Q[s[0],s[1],:])
|
| 209 |
+
self.ls=s; self.la=a
|
| 210 |
+
return min(v*self.bm[a],self.remaining_budget)
|
| 211 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 212 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 213 |
+
if self.ls is not None:
|
| 214 |
+
r=(pctr*self.vpc) if won else 0.0
|
| 215 |
+
ns=self._s(pctr)
|
| 216 |
+
old=self.Q[self.ls[0],self.ls[1],self.la]
|
| 217 |
+
self.Q[self.ls[0],self.ls[1],self.la]=old+self.lr*(r+self.gamma*np.max(self.Q[ns[0],ns[1],:])-old)
|
| 218 |
+
def get_stats(self):
|
| 219 |
+
return {'name':self.name,'spent':float(self.total_spent),'remaining':float(self.remaining_budget),
|
| 220 |
+
'wins':self.total_wins,'t':self.t}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
class LinearBidder:
|
| 224 |
+
"""## Linear β Proportional Bidding Baseline. bid = base_bid Γ (pCTR/avg_pCTR). No adaptation. Serves as lower bound."""
|
| 225 |
+
def __init__(self,base_bid,avg_pctr,name="Linear"):
|
| 226 |
+
self.base_bid=base_bid; self.avg_pctr=avg_pctr; self.name=name
|
| 227 |
+
self.total_spent=0.0; self.remaining_budget=1e9; self.total_wins=0; self.t=0
|
| 228 |
+
def bid(self,pctr,features=None):
|
| 229 |
+
self.t+=1
|
| 230 |
+
if self.remaining_budget<=0: return 0.0
|
| 231 |
+
return min(self.base_bid*(pctr/max(self.avg_pctr,1e-6)),self.remaining_budget)
|
| 232 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 233 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 234 |
+
def set_budget(self,b): self.remaining_budget=b
|
| 235 |
+
def get_stats(self):
|
| 236 |
+
return {'name':self.name,'spent':float(self.total_spent),'remaining':float(self.remaining_budget),
|
| 237 |
+
'wins':self.total_wins,'t':self.t}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class ThresholdBidder:
|
| 241 |
+
"""## Threshold β Binary Bidding Baseline. Fixed bid if pCTR > threshold, else skip. Common rule of thumb."""
|
| 242 |
+
def __init__(self,threshold,bid_value,name="Threshold"):
|
| 243 |
+
self.threshold=threshold; self.bid_value=bid_value; self.name=name
|
| 244 |
+
self.total_spent=0.0; self.remaining_budget=1e9; self.total_wins=0; self.t=0
|
| 245 |
+
def bid(self,pctr,features=None):
|
| 246 |
+
self.t+=1
|
| 247 |
+
if self.remaining_budget<self.bid_value: return 0.0
|
| 248 |
+
return self.bid_value if pctr>self.threshold else 0.0
|
| 249 |
+
def update(self,won,cost,pctr,d_t=None):
|
| 250 |
+
if won: self.total_spent+=cost; self.remaining_budget-=cost; self.total_wins+=1
|
| 251 |
+
def set_budget(self,b): self.remaining_budget=b
|
| 252 |
+
def get_stats(self):
|
| 253 |
+
return {'name':self.name,'spent':float(self.total_spent),'remaining':float(self.remaining_budget),
|
| 254 |
+
'wins':self.total_wins,'t':self.t}
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 258 |
+
# FIRST-PRICE AUCTION SIMULATOR
|
| 259 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 260 |
+
|
| 261 |
+
class FPSim:
|
| 262 |
+
"""
|
| 263 |
+
First-Price Auction Simulator.
|
| 264 |
+
|
| 265 |
+
Simulates repeated first-price auctions. The maximum competing bid d_t
|
| 266 |
+
follows a log-normal distribution whose mean correlates with impression
|
| 267 |
+
quality (pCTR) β realistic: popular impressions attract more competition.
|
| 268 |
+
|
| 269 |
+
Full information feedback: after each auction, d_t is revealed regardless
|
| 270 |
+
of whether we won. This enables empirical CDF approaches.
|
| 271 |
+
"""
|
| 272 |
+
def __init__(self,X,pctr,y,vpc=50,cfg=None,seed=42):
|
| 273 |
+
self.X=X; self.pctr=pctr; self.y=y; self.vpc=vpc; self.N=len(X)
|
| 274 |
+
self.rng=np.random.RandomState(seed)
|
| 275 |
+
cfg=cfg or {}
|
| 276 |
+
bm=cfg.get('base_mean',20); cc=cfg.get('ctr_correlation',10); ns=cfg.get('noise_std',0.6)
|
| 277 |
+
mp=np.clip(bm+cc*self.pctr,1,200)
|
| 278 |
+
self.mp=self.rng.lognormal(np.log(mp),ns,self.N)
|
| 279 |
+
if self.X.shape[1]>1: self.mp*=np.exp((0.02*self.X[:,0]+0.01*self.X[:,1])*0.1)
|
| 280 |
+
self.mp=np.clip(self.mp,0.5,500)
|
| 281 |
+
self.pos=0; self.order=self.rng.permutation(self.N)
|
| 282 |
+
def reset(self): self.pos=0; self.order=self.rng.permutation(self.N)
|
| 283 |
+
def run(self,algo):
|
| 284 |
+
self.reset()
|
| 285 |
+
if hasattr(algo,'set_budget'): algo.set_budget(algo.B if hasattr(algo,'B') else 5000)
|
| 286 |
+
tc=0; bl,wl,cl=[],[],[]
|
| 287 |
+
while self.pos<self.N:
|
| 288 |
+
idx=self.order[self.pos]; self.pos+=1
|
| 289 |
+
bid=algo.bid(self.pctr[idx],self.X[idx])
|
| 290 |
+
rem=algo.remaining_budget if hasattr(algo,'remaining_budget') else 1e9
|
| 291 |
+
bid=np.clip(bid,0,rem)
|
| 292 |
+
mp=self.mp[idx]; won=bid>=mp; cost=bid if won else 0.0
|
| 293 |
+
if won: tc+=int(self.y[idx])
|
| 294 |
+
algo.update(won,cost,self.pctr[idx],mp)
|
| 295 |
+
bl.append(bid); wl.append(int(won)); cl.append(cost)
|
| 296 |
+
s=algo.get_stats()
|
| 297 |
+
s.update({'total_clicks':tc,'total_impressions':len(bl),'total_wins':sum(wl),
|
| 298 |
+
'total_spent':sum(cl),'ctr':tc/max(sum(wl),1),
|
| 299 |
+
'budget_used_frac':sum(cl)/algo.B if hasattr(algo,'B') else 0,
|
| 300 |
+
'cpc':sum(cl)/max(tc,1),'avg_bid':float(np.mean(bl)),
|
| 301 |
+
'win_rate':sum(wl)/max(len(wl),1),
|
| 302 |
+
'avg_market_price':float(np.mean(self.mp))})
|
| 303 |
+
return s
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββββββββββββ
|
| 307 |
+
# DATA LOADING
|
| 308 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 309 |
+
|
| 310 |
+
def load_data(max_rows=200000,seed=42):
|
| 311 |
+
"""
|
| 312 |
+
Load and preprocess Criteo_x4.
|
| 313 |
+
|
| 314 |
+
NOTE: Criteo_x4 is 5.6GB across 37 Parquet files. Streaming 200K rows
|
| 315 |
+
takes ~7 minutes due to sequential Parquet scanning. For quick iteration:
|
| 316 |
+
--max_rows 20000 (loads in ~45 seconds)
|
| 317 |
+
"""
|
| 318 |
+
print(f"\nLoading Criteo_x4 ({max_rows} rows)...")
|
| 319 |
+
ds=load_dataset("reczoo/Criteo_x4",split="train",streaming=True)
|
| 320 |
+
rows=[row for i,row in enumerate(ds) if i<max_rows]
|
| 321 |
+
df=pd.DataFrame(rows)
|
| 322 |
+
print(f" Loaded {len(df)} rows | CTR: {df['Label'].mean():.4f}")
|
| 323 |
+
dc=[f'I{i}' for i in range(1,14)]; sc=[f'C{i}' for i in range(1,27)]
|
| 324 |
+
for c in dc: df[c]=df[c].fillna(df[c].median())
|
| 325 |
+
for c in sc: df[c]=LabelEncoder().fit_transform(df[c].fillna("MISSING").astype(str))
|
| 326 |
+
dd=StandardScaler().fit_transform(df[dc].values)
|
| 327 |
+
for i,c in enumerate(dc): df[c]=dd[:,i]
|
| 328 |
+
sd=df[sc].values.astype(np.float32)
|
| 329 |
+
sd=(sd-sd.mean(0))/(sd.std(0)+1e-8)
|
| 330 |
+
for i,c in enumerate(sc): df[c]=sd[:,i]
|
| 331 |
+
X=df[dc+sc].values.astype(np.float32); y=df['Label'].values.astype(np.float32)
|
| 332 |
+
Xt,Xe,yt,ye=train_test_split(X,y,test_size=0.3,random_state=seed)
|
| 333 |
+
return Xt,Xe,yt,ye
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
+
# MAIN
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
|
| 340 |
+
def main():
|
| 341 |
+
p=argparse.ArgumentParser(description='RTB Bidding Benchmark β First-Price Auctions')
|
| 342 |
+
p.add_argument('--max_rows',type=int,default=200000)
|
| 343 |
+
p.add_argument('--budget',type=float,default=10000)
|
| 344 |
+
p.add_argument('--T',type=int,default=10000)
|
| 345 |
+
p.add_argument('--vpc',type=float,default=50)
|
| 346 |
+
p.add_argument('--k',type=float,default=0.8)
|
| 347 |
+
p.add_argument('--n_runs',type=int,default=5)
|
| 348 |
+
p.add_argument('--output',type=str,default='results/benchmark_results.json')
|
| 349 |
+
p.add_argument('--seed',type=int,default=42)
|
| 350 |
+
args=p.parse_args()
|
| 351 |
+
os.makedirs('results',exist_ok=True)
|
| 352 |
+
t0=time.time()
|
| 353 |
+
print("="*60+"\nRTB BIDDING BENCHMARK β FIRST-PRICE AUCTIONS\n"+"="*60)
|
| 354 |
+
print(f"Data: {args.max_rows} rows | Budget: {args.budget} | Auctions: {args.T} | VPC: {args.vpc} | Runs: {args.n_runs}")
|
| 355 |
+
print(f"Min spend: {args.k*100:.0f}%")
|
| 356 |
+
|
| 357 |
+
Xt,Xe,yt,ye=load_data(args.max_rows,args.seed)
|
| 358 |
+
print(f"Data load: {time.time()-t0:.0f}s")
|
| 359 |
+
|
| 360 |
+
ctr=LogisticRegression(max_iter=500,C=0.1,random_state=42)
|
| 361 |
+
ctr.fit(Xt,yt)
|
| 362 |
+
eauc=roc_auc_score(ye,ctr.predict_proba(Xe)[:,1])
|
| 363 |
+
print(f"CTR AUC: test={eauc:.4f}")
|
| 364 |
+
|
| 365 |
+
pctr=ctr.predict_proba(Xe)[:,1]
|
| 366 |
+
print(f"pCTR: mean={pctr.mean():.4f} range=[{pctr.min():.2f},{pctr.max():.2f}]")
|
| 367 |
+
|
| 368 |
+
all_results={}
|
| 369 |
+
for run in range(args.n_runs):
|
| 370 |
+
rs=args.seed+run
|
| 371 |
+
print(f"\n--- Run {run+1}/{args.n_runs} (seed={rs}) ---")
|
| 372 |
+
sim=FPSim(Xe[:args.T],pctr[:args.T],ye[:args.T],vpc=args.vpc,
|
| 373 |
+
cfg={'base_mean':20,'ctr_correlation':10,'noise_std':0.6},seed=rs)
|
| 374 |
+
algos={
|
| 375 |
+
'DualOGD':DualOGDBidder(args.budget,args.T,args.vpc),
|
| 376 |
+
'TwoSidedDual':TwoSidedDualBidder(args.budget,args.T,args.vpc,k=args.k),
|
| 377 |
+
'ValueShading':ValueShadingBidder(args.budget,args.T,args.vpc),
|
| 378 |
+
'RLB':RLBBidder(args.budget,args.T,args.vpc),
|
| 379 |
+
'Linear':LinearBidder(20.0,float(pctr.mean())),
|
| 380 |
+
'Threshold':ThresholdBidder(0.3,30.0),
|
| 381 |
+
}
|
| 382 |
+
for a in algos.values():
|
| 383 |
+
if hasattr(a,'B'): a.B=args.budget; a.remaining_budget=args.budget
|
| 384 |
+
for name,algo in algos.items():
|
| 385 |
+
r=sim.run(algo)
|
| 386 |
+
if name not in all_results: all_results[name]=[]
|
| 387 |
+
all_results[name].append(r)
|
| 388 |
+
print(f" {name:<16} clicks={r['total_clicks']:>4} spent={r['total_spent']:>8.1f} "
|
| 389 |
+
f"budget={r['budget_used_frac']:.1%} CPC={r['cpc']:.2f}")
|
| 390 |
+
|
| 391 |
+
print(f"\n{'='*60}\nFINAL RESULTS ({args.n_runs} runs)\n{'='*60}")
|
| 392 |
+
print(f"{'Algorithm':<18} {'Clicks':>10} {'CPC':>9} {'Budget%':>9} {'WinRate':>8}")
|
| 393 |
+
print("-"*58)
|
| 394 |
+
aggregated={}
|
| 395 |
+
for name,runs in all_results.items():
|
| 396 |
+
clicks=[r['total_clicks'] for r in runs]
|
| 397 |
+
cpc=[r['cpc'] for r in runs]
|
| 398 |
+
bu=[r['budget_used_frac'] for r in runs]
|
| 399 |
+
wr=[r['win_rate'] for r in runs]
|
| 400 |
+
aggregated[name]={
|
| 401 |
+
'clicks_mean':float(np.mean(clicks)),'clicks_std':float(np.std(clicks)),
|
| 402 |
+
'cpc_mean':float(np.mean(cpc)),'cpc_std':float(np.std(cpc)),
|
| 403 |
+
'budget_used_mean':float(np.mean(bu)),'budget_used_std':float(np.std(bu)),
|
| 404 |
+
'win_rate_mean':float(np.mean(wr)),'win_rate_std':float(np.std(wr))}
|
| 405 |
+
ranked=sorted(aggregated.items(),key=lambda x:x[1]['clicks_mean'],reverse=True)
|
| 406 |
+
for i,(name,s) in enumerate(ranked):
|
| 407 |
+
medal=['π₯','π₯','π₯'][i] if i<3 else ' '
|
| 408 |
+
print(f"{medal} {name:<16} {s['clicks_mean']:>7.0f}Β±{s['clicks_std']:.0f} "
|
| 409 |
+
f"{s['cpc_mean']:>7.2f} {s['budget_used_mean']:>7.1%} {s['win_rate_mean']:>6.1%}")
|
| 410 |
+
|
| 411 |
+
output={'config':{'max_rows':args.max_rows,'budget':args.budget,'T':args.T,
|
| 412 |
+
'vpc':args.vpc,'k':args.k,'n_runs':args.n_runs,'seed':args.seed,
|
| 413 |
+
'ctr_test_auc':float(eauc)},'aggregated':aggregated}
|
| 414 |
+
with open(args.output,'w') as f: json.dump(output,f,indent=2)
|
| 415 |
+
print(f"\nSaved to {args.output}")
|
| 416 |
+
print(f"Total time: {time.time()-t0:.0f}s β Done!")
|
| 417 |
+
|
| 418 |
+
if __name__=='__main__': main()
|