def grpo_step(task, theta, K, reward, rng, beta=0.04, epsilon=0.2,
num_epochs=4, lr=2.0):
"""One group of K responses per prompt, reused for num_epochs clipped
ascent steps with the k3 penalty; returns theta and each epoch's ratios."""
pi_old, n = task.policy(theta), len(task.resp)
ys = np.stack([rng.choice(n, K, p=p) for p in pi_old]) # (prompts, K)
A = np.stack([d2l.standardize(np.array([reward(x, y) for y in ys[x]]))
for x in range(len(ys))])
rows, onehot, ratios = np.arange(len(ys))[:, None], np.eye(n)[ys], []
for _ in range(num_epochs):
pi = task.policy(theta)
rho = pi[rows, ys] / pi_old[rows, ys]
live = np.where(A > 0, rho < 1 + epsilon, rho > 1 - epsilon)
u = live * A * rho - beta * (1 - task.pi_ref[rows, ys] / pi[rows, ys])
theta = theta + lr * np.einsum('xk,xkn->xn', u, onehot - pi[:, None]) / K
ratios.append(rho)
return theta, ratios