bidlab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bidlab/__init__.py ADDED
@@ -0,0 +1,74 @@
1
+ """bidlab: simulate ad auctions to test and compare bidding methods.
2
+
3
+ Examples
4
+ --------
5
+ >>> import bidlab as bl
6
+ >>> config = bl.SimConfig(
7
+ ... campaigns=[
8
+ ... bl.Campaign(
9
+ ... "truthful",
10
+ ... bl.Stack(bl.OracleValue(), bl.Linear()),
11
+ ... budget=50,
12
+ ... base_value=5,
13
+ ... ),
14
+ ... bl.Campaign(
15
+ ... "pid",
16
+ ... bl.Stack(bl.OracleValue(), bl.PidPacing()),
17
+ ... budget=15,
18
+ ... base_value=5,
19
+ ... ),
20
+ ... ],
21
+ ... auction=bl.SecondPrice(reserve=0.01),
22
+ ... episodes=2,
23
+ ... steps=100,
24
+ ... )
25
+ >>> results = bl.run_many(config, seeds=range(2))
26
+ >>> len(results)
27
+ 4
28
+ """
29
+
30
+ from bidlab import bidders, markets
31
+ from bidlab.auctions import FirstPrice, SecondPrice
32
+ from bidlab.bidders import (
33
+ Bidder,
34
+ Linear,
35
+ OracleValue,
36
+ PidPacing,
37
+ Stack,
38
+ UcbMultiplier,
39
+ )
40
+ from bidlab.callbacks import Callback
41
+ from bidlab.config import Campaign, SimConfig
42
+ from bidlab.metrics import campaign_metrics, platform_metrics, regret, segment_metrics
43
+ from bidlab.results import Results
44
+ from bidlab.runner import run_many
45
+ from bidlab.simulator import RunLog, run
46
+ from bidlab.types import BidResult, EpisodeReport, Event, MarketTruth
47
+
48
+ __all__ = [
49
+ "BidResult",
50
+ "Bidder",
51
+ "Callback",
52
+ "Campaign",
53
+ "EpisodeReport",
54
+ "Event",
55
+ "FirstPrice",
56
+ "Linear",
57
+ "MarketTruth",
58
+ "OracleValue",
59
+ "PidPacing",
60
+ "Results",
61
+ "RunLog",
62
+ "SecondPrice",
63
+ "SimConfig",
64
+ "Stack",
65
+ "UcbMultiplier",
66
+ "bidders",
67
+ "campaign_metrics",
68
+ "markets",
69
+ "platform_metrics",
70
+ "regret",
71
+ "run",
72
+ "run_many",
73
+ "segment_metrics",
74
+ ]
bidlab/auctions.py ADDED
@@ -0,0 +1,186 @@
1
+ """Single-slot auctions that pick a winner and a price from the bids."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ NO_WINNER = -1
9
+
10
+
11
+ def _pick_winner(
12
+ bids: npt.NDArray[np.float64],
13
+ floor: float,
14
+ market_price: float | None,
15
+ rng: np.random.Generator,
16
+ ) -> tuple[int, npt.NDArray[np.float64]]:
17
+ eligible = bids >= floor
18
+ # Without a market price, runs skip the extra compare and keep their old path.
19
+ if market_price is not None:
20
+ eligible &= bids > market_price
21
+ valid = np.flatnonzero(eligible)
22
+ if valid.size == 0:
23
+ return NO_WINNER, bids[valid]
24
+
25
+ valid_bids = bids[valid]
26
+ tied = valid[valid_bids == valid_bids.max()]
27
+ winner = int(rng.choice(tied)) if tied.size > 1 else int(tied[0])
28
+ return winner, valid_bids
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class FirstPrice:
33
+ """The winner pays its own bid.
34
+
35
+ The highest bid wins when it is at or above the floor and above the
36
+ market price. The floor is the higher of ``reserve`` and the market's
37
+ floor. Ties are broken at random.
38
+
39
+ Parameters
40
+ ----------
41
+ reserve : float, optional
42
+ Lowest bid that can win. Must be >= 0.
43
+
44
+ Raises
45
+ ------
46
+ ValueError
47
+ If ``reserve`` is negative.
48
+
49
+ See Also
50
+ --------
51
+ SecondPrice : The winner pays the second-highest bid.
52
+
53
+ Examples
54
+ --------
55
+ >>> import numpy as np
56
+ >>> import bidlab as bl
57
+ >>> bl.FirstPrice(reserve=0.1).run(np.array([0.5, 0.3]), np.random.default_rng(0))
58
+ (0, 0.5)
59
+ """
60
+
61
+ reserve: float = 0.0
62
+
63
+ def __post_init__(self) -> None:
64
+ if self.reserve < 0:
65
+ raise ValueError(f"reserve must be >= 0, got {self.reserve}")
66
+
67
+ def run(
68
+ self,
69
+ bids: npt.NDArray[np.float64],
70
+ rng: np.random.Generator,
71
+ *,
72
+ floor: float = 0.0,
73
+ market_price: float | None = None,
74
+ ) -> tuple[int, float]:
75
+ """Pick the winner and the price it pays.
76
+
77
+ Parameters
78
+ ----------
79
+ bids : numpy.ndarray
80
+ One bid per bidder. A bidder that sits out bids ``-inf``.
81
+ rng : numpy.random.Generator
82
+ Breaks ties between equal highest bids.
83
+ floor : float, optional
84
+ The market's floor for this auction; the higher of it and
85
+ ``reserve`` is the lowest bid that can win.
86
+ market_price : float, optional
87
+ The highest bid from outside the bidders; a bid must be above it
88
+ to win. None means no outside bid.
89
+
90
+ Returns
91
+ -------
92
+ winner : int
93
+ Index of the winning bid, or -1 when no bid can win.
94
+ price : float
95
+ Price the winner pays; 0 when there is no winner.
96
+ """
97
+ lowest = max(self.reserve, floor)
98
+ winner, valid_bids = _pick_winner(bids, lowest, market_price, rng)
99
+ if winner == NO_WINNER:
100
+ return NO_WINNER, 0.0
101
+
102
+ return winner, float(valid_bids.max())
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class SecondPrice:
107
+ """The winner pays the highest of the next bid, the floor and the market price.
108
+
109
+ The highest bid wins when it is at or above the floor and above the
110
+ market price. The floor is the higher of ``reserve`` and the market's
111
+ floor. Ties are broken at random. Only bids that can win count as the
112
+ next bid.
113
+
114
+ Parameters
115
+ ----------
116
+ reserve : float, optional
117
+ Lowest bid that can win, and the lowest price. Must be >= 0.
118
+
119
+ Raises
120
+ ------
121
+ ValueError
122
+ If ``reserve`` is negative.
123
+
124
+ See Also
125
+ --------
126
+ FirstPrice : The winner pays its own bid.
127
+
128
+ Examples
129
+ --------
130
+ >>> import numpy as np
131
+ >>> import bidlab as bl
132
+ >>> auction = bl.SecondPrice(reserve=0.1)
133
+ >>> auction.run(np.array([0.5, 0.3]), np.random.default_rng(0))
134
+ (0, 0.3)
135
+ >>> auction.run(np.array([0.5, 0.05]), np.random.default_rng(0))
136
+ (0, 0.1)
137
+ """
138
+
139
+ reserve: float = 0.0
140
+
141
+ def __post_init__(self) -> None:
142
+ if self.reserve < 0:
143
+ raise ValueError(f"reserve must be >= 0, got {self.reserve}")
144
+
145
+ def run(
146
+ self,
147
+ bids: npt.NDArray[np.float64],
148
+ rng: np.random.Generator,
149
+ *,
150
+ floor: float = 0.0,
151
+ market_price: float | None = None,
152
+ ) -> tuple[int, float]:
153
+ """Pick the winner and the price it pays.
154
+
155
+ Parameters
156
+ ----------
157
+ bids : numpy.ndarray
158
+ One bid per bidder. A bidder that sits out bids ``-inf``.
159
+ rng : numpy.random.Generator
160
+ Breaks ties between equal highest bids.
161
+ floor : float, optional
162
+ The market's floor for this auction; the higher of it and
163
+ ``reserve`` is the lowest bid that can win.
164
+ market_price : float, optional
165
+ The highest bid from outside the bidders; a bid must be above it
166
+ to win. None means no outside bid.
167
+
168
+ Returns
169
+ -------
170
+ winner : int
171
+ Index of the winning bid, or -1 when no bid can win.
172
+ price : float
173
+ Price the winner pays; 0 when there is no winner.
174
+ """
175
+ lowest = max(self.reserve, floor)
176
+ winner, valid_bids = _pick_winner(bids, lowest, market_price, rng)
177
+ if winner == NO_WINNER:
178
+ return NO_WINNER, 0.0
179
+
180
+ second = np.sort(valid_bids)[-2] if valid_bids.size > 1 else lowest
181
+ # The floor is >= 0, so 0 stands in for no market price.
182
+ outside = 0.0 if market_price is None else market_price
183
+ return winner, float(max(second, lowest, outside))
184
+
185
+
186
+ Auction = FirstPrice | SecondPrice
@@ -0,0 +1,27 @@
1
+ """Built-in bidders, grouped by family, and the `Bidder` and `Stack` classes.
2
+
3
+ | Family | Bidders |
4
+ |---|---|
5
+ | `baselines` | `Linear`, `OracleValue` |
6
+ | `pacing` | `PidPacing` |
7
+ | `bandits` | `UcbMultiplier` |
8
+ """
9
+
10
+ from bidlab.bidders import bandits, baselines, pacing
11
+ from bidlab.bidders.bandits import UcbMultiplier
12
+ from bidlab.bidders.base import Bidder
13
+ from bidlab.bidders.baselines import Linear, OracleValue
14
+ from bidlab.bidders.pacing import PidPacing
15
+ from bidlab.bidders.stack import Stack
16
+
17
+ __all__ = [
18
+ "Bidder",
19
+ "Linear",
20
+ "OracleValue",
21
+ "PidPacing",
22
+ "Stack",
23
+ "UcbMultiplier",
24
+ "bandits",
25
+ "baselines",
26
+ "pacing",
27
+ ]
@@ -0,0 +1,110 @@
1
+ """Bandit bidders that learn a bid multiplier across episodes."""
2
+
3
+ from typing import TYPE_CHECKING, override
4
+
5
+ import numpy as np
6
+
7
+ from bidlab.bidders.base import Bidder
8
+ from bidlab.types import BidResult, EpisodeReport
9
+
10
+ if TYPE_CHECKING:
11
+ from bidlab.config import Campaign
12
+
13
+ # np.arange excludes its end, so a small margin keeps max_multiplier in the grid.
14
+ ARM_GRID_END_MARGIN = 1e-9
15
+ # Keeps the exploration bonus above zero when every arm has the same mean.
16
+ MIN_REWARD_SCALE = 1e-12
17
+
18
+
19
+ class UcbMultiplier(Bidder):
20
+ """UCB1 over bid multipliers; one arm per episode, learned across episodes.
21
+
22
+ Each arm is a fixed multiplier m, and the bidder outputs m × value for a
23
+ whole episode. An arm's reward is the episode's surplus: the sum of
24
+ ``realized_value - price`` over its results, kept in ``arm_reward``.
25
+ Override `update` to reward something else. The exploration bonus is scaled by
26
+ the spread of the arm means, so it works for any reward unit.
27
+
28
+ Parameters
29
+ ----------
30
+ min_multiplier, max_multiplier : float, optional
31
+ The arm grid's ends, with 0 <= ``min_multiplier`` <= ``max_multiplier``.
32
+ multiplier_step : float, optional
33
+ The grid's spacing. Must be > 0.
34
+ exploration : float, optional
35
+ Scales the exploration bonus. Must be >= 0.
36
+ log_state : bool, optional
37
+ Log the chosen arm's multiplier as ``"multiplier"`` once per episode.
38
+
39
+ Raises
40
+ ------
41
+ ValueError
42
+ If an argument is out of range.
43
+
44
+ Examples
45
+ --------
46
+ >>> import bidlab as bl
47
+ >>> bl.UcbMultiplier(multiplier_step=0.6).arms.round(1).tolist()
48
+ [0.2, 0.8, 1.4, 2.0]
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ min_multiplier: float = 0.2,
54
+ max_multiplier: float = 2.0,
55
+ multiplier_step: float = 0.2,
56
+ exploration: float = 1.0,
57
+ log_state: bool = True,
58
+ ):
59
+ if not 0 <= min_multiplier <= max_multiplier:
60
+ raise ValueError(
61
+ "need 0 <= min_multiplier <= max_multiplier, got "
62
+ f"{min_multiplier} and {max_multiplier}"
63
+ )
64
+
65
+ if multiplier_step <= 0:
66
+ raise ValueError(f"multiplier_step must be > 0, got {multiplier_step}")
67
+
68
+ if exploration < 0:
69
+ raise ValueError(f"exploration must be >= 0, got {exploration}")
70
+
71
+ self.arms = np.arange(
72
+ min_multiplier, max_multiplier + ARM_GRID_END_MARGIN, multiplier_step
73
+ )
74
+ self.exploration = exploration
75
+ self.log_state = log_state
76
+ self.pulls = np.zeros(self.arms.size)
77
+ self.reward_sums = np.zeros(self.arms.size)
78
+ self.arm = 0
79
+ self.arm_reward = 0.0
80
+
81
+ @override
82
+ def on_episode_start(self, campaign: "Campaign") -> None:
83
+ self.arm = self._choose_arm()
84
+ self.arm_reward = 0.0
85
+ if self.log_state:
86
+ self.log("multiplier", float(self.arms[self.arm]))
87
+
88
+ @override
89
+ def forward(self, value: float) -> float:
90
+ return float(self.arms[self.arm]) * value
91
+
92
+ @override
93
+ def update(self, result: BidResult) -> None:
94
+ self.arm_reward += result.realized_value - result.price
95
+
96
+ @override
97
+ def on_episode_end(self, report: EpisodeReport) -> None:
98
+ self.pulls[self.arm] += 1
99
+ self.reward_sums[self.arm] += self.arm_reward
100
+
101
+ def _choose_arm(self) -> int:
102
+ untried = np.flatnonzero(self.pulls == 0)
103
+ if untried.size:
104
+ return int(untried[0])
105
+
106
+ means = self.reward_sums / self.pulls
107
+ # Scaling the bonus by the reward range makes it work for any reward unit.
108
+ scale = max(means.max() - means.min(), MIN_REWARD_SCALE)
109
+ bonus = scale * np.sqrt(2 * np.log(self.pulls.sum()) / self.pulls)
110
+ return int(np.argmax(means + self.exploration * bonus))