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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
First-Price Auction Simulator for RTB Bidding Benchmark
|
| 3 |
+
|
| 4 |
+
Simulates a stream of first-price auctions with:
|
| 5 |
+
- Impression features (from Criteo_x4 for CTR)
|
| 6 |
+
- Click labels (ground truth from Criteo)
|
| 7 |
+
- Synthetic market prices (competing bids) conditioned on features
|
| 8 |
+
- Full information feedback (observes all competing bids)
|
| 9 |
+
|
| 10 |
+
Used to evaluate bidding algorithms under controlled conditions.
|
| 11 |
+
"""
|
| 12 |
+
import numpy as np
|
| 13 |
+
from collections import defaultdict
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class FirstPriceAuctionSimulator:
|
| 17 |
+
"""
|
| 18 |
+
Simulates repeated first-price auctions.
|
| 19 |
+
|
| 20 |
+
In a first-price auction:
|
| 21 |
+
- Each bidder submits a sealed bid
|
| 22 |
+
- Highest bidder wins and pays their bid
|
| 23 |
+
- Losing bidders pay nothing
|
| 24 |
+
|
| 25 |
+
We simulate the "advertiser" (our bidder) vs. a pool of competing bidders.
|
| 26 |
+
The maximum competing bid d_t follows a distribution conditioned on features.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
features,
|
| 32 |
+
pctr_true,
|
| 33 |
+
click_labels,
|
| 34 |
+
value_per_click=50.0,
|
| 35 |
+
market_price_config=None,
|
| 36 |
+
seed=42
|
| 37 |
+
):
|
| 38 |
+
"""
|
| 39 |
+
Args:
|
| 40 |
+
features: (N, D) impression feature matrix
|
| 41 |
+
pctr_true: (N,) true or predicted CTR values
|
| 42 |
+
click_labels: (N,) binary click labels
|
| 43 |
+
value_per_click: Value of each click in currency
|
| 44 |
+
market_price_config: Dict controlling price generation
|
| 45 |
+
seed: Random seed
|
| 46 |
+
"""
|
| 47 |
+
self.features = features
|
| 48 |
+
self.pctr_true = pctr_true
|
| 49 |
+
self.click_labels = click_labels
|
| 50 |
+
self.value_per_click = value_per_click
|
| 51 |
+
self.N = len(features)
|
| 52 |
+
self.rng = np.random.RandomState(seed)
|
| 53 |
+
|
| 54 |
+
# Generate synthetic market prices
|
| 55 |
+
self.market_prices = self._generate_market_prices(market_price_config or {})
|
| 56 |
+
|
| 57 |
+
# Shuffle indices
|
| 58 |
+
self.order = self.rng.permutation(self.N)
|
| 59 |
+
self.position = 0
|
| 60 |
+
|
| 61 |
+
def _generate_market_prices(self, config):
|
| 62 |
+
"""
|
| 63 |
+
Generate synthetic market prices (max competing bids).
|
| 64 |
+
|
| 65 |
+
Prices are conditioned on features: higher-CTR impressions tend to
|
| 66 |
+
have higher competition (more bidders want them).
|
| 67 |
+
|
| 68 |
+
Default: log-normal distribution with mean correlated to pCTR.
|
| 69 |
+
"""
|
| 70 |
+
base_mean = config.get('base_mean', 20.0)
|
| 71 |
+
ctr_correlation = config.get('ctr_correlation', 10.0)
|
| 72 |
+
noise_std = config.get('noise_std', 0.6)
|
| 73 |
+
price_multiplier = config.get('price_multiplier', 1.0)
|
| 74 |
+
|
| 75 |
+
N = self.N
|
| 76 |
+
|
| 77 |
+
# Mean price increases with CTR (popular impressions cost more)
|
| 78 |
+
mean_prices = base_mean + ctr_correlation * self.pctr_true
|
| 79 |
+
mean_prices = np.clip(mean_prices, 1.0, 200.0)
|
| 80 |
+
|
| 81 |
+
# Log-normal noise
|
| 82 |
+
prices = self.rng.lognormal(
|
| 83 |
+
mean=np.log(mean_prices),
|
| 84 |
+
sigma=noise_std,
|
| 85 |
+
size=N
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# Scale
|
| 89 |
+
prices = prices * price_multiplier
|
| 90 |
+
|
| 91 |
+
# Add feature-dependent variation
|
| 92 |
+
if self.features.shape[1] > 1:
|
| 93 |
+
# Use first two features to add correlated variation
|
| 94 |
+
feature_effect = (
|
| 95 |
+
0.02 * self.features[:, 0] +
|
| 96 |
+
0.01 * self.features[:, 1]
|
| 97 |
+
)
|
| 98 |
+
prices = prices * np.exp(feature_effect * 0.1)
|
| 99 |
+
|
| 100 |
+
return np.clip(prices, 0.5, 500.0)
|
| 101 |
+
|
| 102 |
+
def reset(self):
|
| 103 |
+
"""Reset simulator to beginning of auction sequence."""
|
| 104 |
+
self.position = 0
|
| 105 |
+
self.order = self.rng.permutation(self.N)
|
| 106 |
+
|
| 107 |
+
def next_auction(self):
|
| 108 |
+
"""
|
| 109 |
+
Return next auction: (features, pctr, true_click, market_price).
|
| 110 |
+
Returns None when exhausted.
|
| 111 |
+
"""
|
| 112 |
+
if self.position >= self.N:
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
idx = self.order[self.position]
|
| 116 |
+
self.position += 1
|
| 117 |
+
|
| 118 |
+
return (
|
| 119 |
+
self.features[idx],
|
| 120 |
+
self.pctr_true[idx],
|
| 121 |
+
int(self.click_labels[idx]),
|
| 122 |
+
self.market_prices[idx]
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def simulate_bid(self, bid):
|
| 126 |
+
"""
|
| 127 |
+
Simulate the outcome of placing a bid in the current auction.
|
| 128 |
+
|
| 129 |
+
Must be called after next_auction().
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
bid: Bid price
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
(won, cost, click_occurred)
|
| 136 |
+
"""
|
| 137 |
+
_, _, click, market_price = (
|
| 138 |
+
self.features[self.order[self.position - 1]],
|
| 139 |
+
self.pctr_true[self.order[self.position - 1]],
|
| 140 |
+
int(self.click_labels[self.order[self.position - 1]]),
|
| 141 |
+
self.market_prices[self.order[self.position - 1]]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
won = bid >= market_price
|
| 145 |
+
cost = bid if won else 0.0
|
| 146 |
+
click_occurred = click if won else 0
|
| 147 |
+
|
| 148 |
+
return won, cost, click_occurred, market_price
|
| 149 |
+
|
| 150 |
+
def run_algorithm(self, algo, ctr_predictor=None):
|
| 151 |
+
"""
|
| 152 |
+
Run a bidding algorithm through the full auction sequence.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
algo: Bidding algorithm instance with .bid(pctr) and .update(won, cost, pctr, d_t)
|
| 156 |
+
ctr_predictor: Optional CTRPredictor. If None, uses self.pctr_true.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
results dict with metrics
|
| 160 |
+
"""
|
| 161 |
+
self.reset()
|
| 162 |
+
|
| 163 |
+
# Set budget on algorithm if it supports it
|
| 164 |
+
if hasattr(algo, 'set_budget'):
|
| 165 |
+
algo.set_budget(algo.B if hasattr(algo, 'B') else 5000)
|
| 166 |
+
|
| 167 |
+
metrics = defaultdict(list)
|
| 168 |
+
total_clicks = 0
|
| 169 |
+
|
| 170 |
+
while True:
|
| 171 |
+
auction = self.next_auction()
|
| 172 |
+
if auction is None:
|
| 173 |
+
break
|
| 174 |
+
|
| 175 |
+
features, _, true_click, market_price = auction
|
| 176 |
+
|
| 177 |
+
# Get CTR prediction
|
| 178 |
+
if ctr_predictor is not None:
|
| 179 |
+
# Use learned CTR model
|
| 180 |
+
pctr = ctr_predictor.predict_single({
|
| 181 |
+
f'I{i+1}': features[i] for i in range(13)
|
| 182 |
+
} | {
|
| 183 |
+
f'C{i+1}': features[13+i] for i in range(26)
|
| 184 |
+
})
|
| 185 |
+
else:
|
| 186 |
+
pctr = self.pctr_true[self.order[self.position - 1]]
|
| 187 |
+
|
| 188 |
+
# Place bid
|
| 189 |
+
bid = algo.bid(pctr, features)
|
| 190 |
+
bid = np.clip(bid, 0, algo.remaining_budget if hasattr(algo, 'remaining_budget') else float('inf'))
|
| 191 |
+
|
| 192 |
+
# Simulate outcome
|
| 193 |
+
won, cost, click, d_t = self.simulate_bid(bid)
|
| 194 |
+
|
| 195 |
+
if won:
|
| 196 |
+
total_clicks += click
|
| 197 |
+
|
| 198 |
+
# Update algorithm
|
| 199 |
+
algo.update(won, cost, pctr, d_t)
|
| 200 |
+
|
| 201 |
+
# Track metrics
|
| 202 |
+
metrics['bids'].append(bid)
|
| 203 |
+
metrics['won'].append(int(won))
|
| 204 |
+
metrics['cost'].append(cost)
|
| 205 |
+
metrics['pctr'].append(pctr)
|
| 206 |
+
metrics['market_price'].append(market_price)
|
| 207 |
+
|
| 208 |
+
# Compute summary
|
| 209 |
+
results = algo.get_stats()
|
| 210 |
+
results.update({
|
| 211 |
+
'total_clicks': total_clicks,
|
| 212 |
+
'total_impressions': len(metrics['bids']),
|
| 213 |
+
'total_wins': sum(metrics['won']),
|
| 214 |
+
'total_spent': sum(metrics['cost']),
|
| 215 |
+
'ctr': total_clicks / max(sum(metrics['won']), 1),
|
| 216 |
+
'budget_used_frac': sum(metrics['cost']) / algo.B if hasattr(algo, 'B') else 0,
|
| 217 |
+
'cpc': sum(metrics['cost']) / max(total_clicks, 1),
|
| 218 |
+
'avg_bid': np.mean(metrics['bids']),
|
| 219 |
+
'win_rate': sum(metrics['won']) / max(len(metrics['won']), 1),
|
| 220 |
+
'avg_market_price': np.mean(metrics['market_price']),
|
| 221 |
+
})
|
| 222 |
+
|
| 223 |
+
return results
|
| 224 |
+
|
| 225 |
+
def run_comparison(self, algorithms, ctr_predictor=None):
|
| 226 |
+
"""
|
| 227 |
+
Run multiple algorithms on the same auction sequence and compare.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
algorithms: Dict of {name: algorithm_instance}
|
| 231 |
+
ctr_predictor: Shared CTR predictor
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
Dict of {name: results_dict}
|
| 235 |
+
"""
|
| 236 |
+
all_results = {}
|
| 237 |
+
|
| 238 |
+
for name, algo in algorithms.items():
|
| 239 |
+
print(f"\nRunning {name}...")
|
| 240 |
+
results = self.run_algorithm(algo, ctr_predictor)
|
| 241 |
+
all_results[name] = results
|
| 242 |
+
|
| 243 |
+
print(f" Clicks: {results['total_clicks']}")
|
| 244 |
+
print(f" Spend: {results['total_spent']:.2f}")
|
| 245 |
+
print(f" Budget used: {results.get('budget_used_frac', 0):.1%}")
|
| 246 |
+
print(f" CPC: {results.get('cpc', 0):.2f}")
|
| 247 |
+
|
| 248 |
+
return all_results
|