"""RCB: Recommendation Contextual Bandit (Li, Cheng, Dai; ICML 2026, arXiv 2406.04374). Faithful implementation of Algorithm 1 (Cold Start Stage) and Algorithm 2 (Exploitation Stage) with the inverse proportional gap sampling (IPGS) kernel of Eq. (6), the DBIC calibration constants N(eps), L(eps) of Theorem 1, and the epoch/spread schedule gamma_m = 4 sqrt(K / E_{F,delta}(|T_{m-1}|)). Notation follows the paper: K number of arms (products) d covariate dimension x_t stochastic covariate of user t (a *random* draw, not fixed design) mu(x,i) = x' beta_i (+ offset) mean reward of arm i P_{i,0} = N(beta_{i,0}, Sigma_{i,0}) public Gaussian prior over beta_i """ import numpy as np # ---------------------------------------------------------------- Theorem 1 def N_eps(K, d, sigma, eps, tau, phi0, C=1.0): """Cold-start per-arm sample size, Theorem 1 Eq. (7): N(eps) >= (sigma^2 d + 1) K^3 / ( phi0 (tau_{P*} + eps)^2 ). `C` is the implementation constant left unspecified by the paper (the proof, Eq. C.20, carries unresolved constants c2, c3 from Corollary 1). It rescales N but leaves every exponent -- the content of Theorem 1 -- untouched. """ return C * (sigma ** 2 * d + 1.0) * K ** 3 / (phi0 * (tau + eps) ** 2) def L_eps(eps, tau_P0, rho_P0, delta_max=1.0): """Inverse exploration probability, Theorem 1 Eq. (7) / proof Eq. (C.11): L >= 1 + (Delta0 - eps) / (tau_{P0} rho_{P0} + eps), Delta0 <= 1. The paper states the worst case Delta0 = 1, giving L >= 1 + (1-eps)/(tau rho + eps). """ return 1.0 + (delta_max - eps) / (tau_P0 * rho_P0 + eps) def m0_eps(N): """Epoch at which the Exploitation stage starts: m0 = ceil(2 + log2 N).""" return int(np.ceil(2.0 + np.log2(max(N, 1.0)))) def EF_ridge(n, d, sigma, phi0, c3=1.0): """Ridge / random-design generalization error, Corollary 1: c3 sigma^2 d / (phi0 n).""" return c3 * sigma ** 2 * d / (phi0 * max(n, 1.0)) # ---------------------------------------------------------------- IPGS, Eq. 6 def ipgs(mu_hat, gamma): """Inverse proportional gap sampling kernel of Eq. (6). p_t(i) = 1 / (K + gamma (mu_hat(x,b_t) - mu_hat(x,i))) for i != b_t p_t(b_t) = 1 - sum_{i != b_t} p_t(i) `mu_hat` is the length-K vector of predicted rewards for the current x_t. """ K = len(mu_hat) b = int(np.argmax(mu_hat)) gaps = mu_hat[b] - mu_hat p = 1.0 / (K + gamma * gaps) p[b] = 0.0 p[b] = 1.0 - p.sum() return p, b # ------------------------------------------------------- Gaussian posteriors class ArmPosterior: """Conjugate Gaussian posterior over beta_i given (x, y) pairs and noise sigma^2. Prior N(beta0, Sigma0); posterior precision Lambda = Sigma0^{-1} + X'X/sigma^2. `trust_scale` implements Assumption 4 (Evolution of Trust): the *prior* covariance is inflated over time so users become more diffuse / open. """ def __init__(self, d, beta0, Sigma0, sigma): self.d = d self.beta0 = np.asarray(beta0, float).copy() self.Sigma0 = np.asarray(Sigma0, float).copy() self.sigma = float(sigma) self.XtX = np.zeros((d, d)) self.Xty = np.zeros(d) self.n = 0 def update(self, x, y): self.XtX += np.outer(x, x) self.Xty += x * y self.n += 1 def _prior_cov(self, trust_scale): return self.Sigma0 * trust_scale def post(self, trust_scale=1.0): S0 = self._prior_cov(trust_scale) S0inv = np.linalg.inv(S0) Lam = S0inv + self.XtX / self.sigma ** 2 Cov = np.linalg.inv(Lam) mean = Cov @ (S0inv @ self.beta0 + self.Xty / self.sigma ** 2) return mean, Cov def post_mean(self, trust_scale=1.0): """Cached: the posterior mean only moves when new data arrives or the Assumption-4 trust scale changes materially, so we key the cache on (n, trust_scale quantized to 1%). Exact to within that quantization.""" key = (self.n, round(np.log(max(trust_scale, 1e-12)) / 0.01)) if getattr(self, "_ck", None) != key: self._ck, self._cv = key, self.post(trust_scale)[0] return self._cv # ------------------------------------------------------------------ the algo class RCB: """Two-stage RCB. Stage 1 = Algorithm 1 (MPASC then RASC); Stage 2 = Algorithm 2.""" def __init__(self, K, d, sigma, beta0, Sigma0, N, L, offset=0.0, phi0=1.0, c3=1.0, trust_mode="linear", trust_rate=1.0, gamma_const=4.0, use_empirical_EF=False, ridge_lam=1e-2, rng=None): self.K, self.d, self.sigma = K, d, float(sigma) self.offset = float(offset) self.N = int(max(1, round(N))) self.L = float(L) self.phi0, self.c3 = float(phi0), float(c3) self.trust_mode, self.trust_rate = trust_mode, float(trust_rate) self.gamma_const = float(gamma_const) self.use_empirical_EF = use_empirical_EF self.ridge_lam = float(ridge_lam) self.rng = rng if rng is not None else np.random.default_rng(0) self.post = [ArmPosterior(d, beta0[i], Sigma0[i], sigma) for i in range(K)] self.beta0 = [np.asarray(b, float) for b in beta0] self.Ni = np.zeros(K, int) # counts of *exploration* pulls (Algorithm 1) self.B = set() # saturated arms B_t self.stage = 1 self.t = 0 self.Tcold = None self.m0 = m0_eps(self.N) # exploitation-stage state self.W = [[] for _ in range(K)] # (x, y) collected, fed to the offline oracle self.beta_hat = [np.asarray(b, float).copy() for b in beta0] self.gamma_m = 1.0 self.cur_m = None self._EF_prev = None # --- Assumption 4: prior covariance inflation --------------------------- def trust_scale(self): t = max(self.t, 1) if self.trust_mode == "none": return 1.0 if self.trust_mode == "linear": return 1.0 + self.trust_rate * t / 1000.0 if self.trust_mode == "sqrt": return 1.0 + self.trust_rate * np.sqrt(t) / 1000.0 if self.trust_mode == "log": return 1.0 + self.trust_rate * np.log(1.0 + t) / 1000.0 raise ValueError(self.trust_mode) # --- belief helpers ----------------------------------------------------- def prior_mean_rewards(self, x): """E[mu(x,i)] under the public prior P_0 -- what a myopic user believes.""" return np.array([self.offset + x @ self.beta0[i] for i in range(self.K)]) def trusted_mean_rewards(self, x): """E[mu(x,i) | S_{B_t}]: posterior mean for saturated arms, prior mean otherwise. This is exactly the conditional expectation appearing in Eq. (5) and in Assumption 1's prior-posterior gap G_t(i). """ ts = self.trust_scale() out = np.empty(self.K) for i in range(self.K): if i in self.B: out[i] = self.offset + x @ self.post[i].post_mean(ts) else: out[i] = self.offset + x @ self.beta0[i] return out def dbic_gain(self, x, rec): """Realized per-round gap for the arm actually recommended: E[mu(x, I_t) | Gamma_{t-1}] - max_{j != I_t} E[mu(x, j) | Gamma_{t-1}]. """ m = self.trusted_mean_rewards(x) return m[rec] - np.max(np.delete(m, rec)) def dbic_gain_expected(self, x, p): """The quantity Definition 1 / Eq. (2) actually constrains, in closed form: sum_i Pr(I_t = i) ( E[mu(x,i)|Gamma] - max_{j != i} E[mu(x,j)|Gamma] ), i.e. the expectation over the recommendation kernel, which is exactly "Part I Reward Gap + Part II Reward Gap" of proof Eq. (C.14). `p` is the recommendation distribution over arms at this round. """ m = self.trusted_mean_rewards(x) g = np.array([m[i] - np.max(np.delete(m, i)) for i in range(self.K)]) return float(p @ g) def rec_kernel(self, x, info): """Recover the recommendation distribution p_t(.) used at this round.""" p = np.zeros(self.K) if "p" in info: return info["p"] if info["phase"] == "MPASC": p[int(np.argmax(self.prior_mean_rewards(x)))] = 1.0 return p # RASC: 1/L on the promoted arm, 1 - 1/L on the organic arm unsat = [i for i in range(self.K) if i not in self.B] org = int(np.argmax(self.trusted_mean_rewards(x))) if unsat: pm = self.prior_mean_rewards(x) prom = max(unsat, key=lambda j: pm[j]) p[prom] += 1.0 / self.L p[org] += 1.0 - 1.0 / self.L else: p[org] = 1.0 return p # --- epoch / oracle bookkeeping ---------------------------------------- def _epoch_of(self, t): return int(np.floor(np.log2(max(t, 1)))) + 1 def _ridge(self, X, y): A = X.T @ X + self.ridge_lam * np.eye(self.d) return np.linalg.solve(A, X.T @ y) def _fit_oracle(self): """Offline oracle Off_F: per-arm ridge regression on the accumulated data. Also returns an estimate of E_{F,delta}(n) (Definition 2): the oracle's mean squared prediction error, measured out-of-fold so it is a genuine *generalization* error rather than an in-sample residual. """ errs, ws = [], [] for i in range(self.K): if len(self.W[i]) == 0: continue X = np.array([w[0] for w in self.W[i]]) y = np.array([w[1] for w in self.W[i]]) - self.offset self.beta_hat[i] = self._ridge(X, y) if len(y) >= 4: # 2-fold out-of-fold MSPE h = len(y) // 2 for tr, te in ((slice(0, h), slice(h, None)), (slice(h, None), slice(0, h))): b = self._ridge(X[tr], y[tr]) errs.append(float(np.mean((X[te] @ b - y[te]) ** 2))) ws.append(X[te].shape[0]) return float(np.average(errs, weights=ws)) if errs else None def _start_epoch(self, m): self.cur_m = m mspe = self._fit_oracle() if self.use_empirical_EF and mspe is not None: # Definition 2 bounds E[(mu_hat - mu)^2], the excess risk w.r.t. the true # *mean* reward, so the irreducible observation noise sigma^2 is removed. EF = max(mspe - self.sigma ** 2, 1e-8) else: n_prev = max(2 ** (m - 2), 1) # |T_{m-1}| = 2^{m-2} EF = EF_ridge(n_prev, self.d, self.sigma, self.phi0, self.c3) self._EF_prev = EF self.gamma_m = self.gamma_const * np.sqrt(self.K / max(EF, 1e-12)) # --- one round ---------------------------------------------------------- def recommend(self, x): """Return (recommended arm I_t, info dict). The DBIC constraint makes a_t = I_t.""" self.t += 1 if self.stage == 1: if len(self.B) == 0: # STEP 1 -- MPASC: recommend the highest context-dependent prior mean i = int(np.argmax(self.prior_mean_rewards(x))) return i, {"phase": "MPASC", "explore": True} # STEP 2 -- RASC q = self.rng.random() < 1.0 / self.L unsat = [i for i in range(self.K) if i not in self.B] if q and unsat: # (a) promoted recommendation, Eq. (4) pm = self.prior_mean_rewards(x) i = max(unsat, key=lambda j: pm[j]) return i, {"phase": "RASC-promote", "explore": True} # (b) organic recommendation, Eq. (5) i = int(np.argmax(self.trusted_mean_rewards(x))) return i, {"phase": "RASC-organic", "explore": False} # ---- Stage 2, Algorithm 2 ---- m = self._epoch_of(self.t) if m != self.cur_m: self._start_epoch(m) mu_hat = np.array([self.offset + x @ self.beta_hat[i] for i in range(self.K)]) p, b = ipgs(mu_hat, self.gamma_m) p = np.clip(p, 0.0, None) p = p / p.sum() i = int(self.rng.choice(self.K, p=p)) return i, {"phase": "IPGS", "explore": i != b, "p": p, "b": b, "gamma": self.gamma_m} def update(self, x, arm, y, info): if self.stage == 1: # organic pulls deliberately do NOT increment N or S (Section 3.1) if info["explore"]: self.post[arm].update(x, y) self.Ni[arm] += 1 self.W[arm].append((x, y)) if self.Ni[arm] >= self.N: self.B.add(arm) if len(self.B) == self.K: self.stage = 2 self.Tcold = self.t self._start_epoch(max(self._epoch_of(self.t), self.m0)) else: self.post[arm].update(x, y) self.W[arm].append((x, y))