851. BYOL target network EMA with cosine tau
Why it matters Momentum encoders appear in BYOL, MoCo, DINO and EMA weights for diffusion models. The cosine schedule for tau is a common detail interviewers probe.
Paper: "Bootstrap your own latent: A new approach to self-supervised Learning", Grill et al., 2020, arXiv 2006.07733.
BYOL's target network is an exponential moving average of the online network: xi <- tau * xi + (1 - tau) * theta. The decay rises over training with a cosine schedule: tau = 1 - (1 - tau_base) * (cos(pi * k / K) + 1) / 2, where k is the current step and K is the total number of steps. The paper uses tau_base = 0.996.
Write byol_target_update(target, online, k, K, tau_base=0.996).
Inputs: target and online are lists or ndarrays of the same shape (any shape). k and K are ints with 0 <= k <= K and K > 0.
Return a tuple (new_target, tau): new_target is an ndarray of floats, tau is a float. At k = 0, tau equals tau_base. At k = K, tau is 1.0 and the target does not move. No rounding.
def byol_target_update(target, online, k, K, tau_base=0.996)Example 1
Input: byol_target_update([1.0, 2.0], [3.0, 0.0], 0, 100)
Output: ([1.008, 1.992], 0.996)
Example 2
Input: target = [1.0, 2.0], online = [3.0, 0.0], k = 50, K = 100
Output: ([1.004, 1.996], 0.998)
Example 3
Input: target = [[0.0, 1.0], [2.0, 3.0]], online = [[1.0, 1.0], [1.0, 1.0]], k = 100, K = 100
Output: ([[0.0, 1.0], [2.0, 3.0]], 1.0)
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Compute tau from the cosine formula first.
Hint 2
new = tau * target + (1 - tau) * online.
Hint 3
Return the float tau as well.
Common mistakes
- Swapping target and online in the update.
- Using cos(pi * k / K) without the + 1 and / 2.
- Decreasing tau over training instead of increasing it.
Understand the idea
The online network learns by gradient descent; the target is a slow average of it that gives stable regression targets. Early on tau is 0.996, so the target moves 0.4 percent of the way each step. At the end tau reaches 1 and the target freezes. Halfway through, cos(pi / 2) = 0, so tau = 1 - 0.004 / 2 = 0.998.
Shapes and data flow
target and online: any matching shape. tau: scalar.