def offline_q(batch, gamma, kappa=0.0, num_iters=500, shape=(16, 4)):
"""Where offline Q-learning with decaying steps converges: value
iteration on the log's empirical MDP. kappa > 0 subtracts
kappa / sqrt(n(s, a)) inside every backup, distrusts untried pairs
entirely, and clips at zero, the floor this environment guarantees."""
n = count(batch, shape)
P, r = np.zeros(shape + shape[:1]), np.zeros(shape)
np.add.at(P, (batch.obs, batch.act, batch.next_obs), 1)
np.add.at(r, (batch.obs, batch.act), batch.rew)
m = np.maximum(n, 1) # untried: rows of zeros
mdp_hat = d2l.TabularMDP(P / m[..., None], r / m, gamma)
penalty = np.where(n > 0, kappa / np.sqrt(m),
np.inf if kappa > 0 else 0.0)
Q = np.zeros(shape)
for _ in range(num_iters):
Q = np.maximum(mdp_hat.backup(Q.max(axis=1)) - penalty, 0.0)
return Q