In many jointly trained models (such as discrete representation learning or self-supervised setups), the total loss contains terms where gradients should only flow to one of two parameter groups. This is achieved with the stop-gradient operator, often written as sg(), which acts as the identity in the forward pass but blocks gradients in the backward pass.
Consider two parameter vectors produced by different branches of a model: an encoder output z_e and a target vector z_q (for example, a codebook entry). A common joint objective is:
L = || sg(z_e) - z_q ||^2 + beta * || z_e - sg(z_q) ||^2
Here the first term only updates z_q and the second term only updates z_e. Implement a function stop_gradient_grads(z_e, z_q, beta) that returns the gradients of L with respect to z_e and z_q, taking the stop-gradient behavior correctly into account.
Return a dictionary with keys 'grad_z_e' and 'grad_z_q', each a numpy array converted to a Python list.