Gated Cross-Attention (Flamingo tanh Gate)
Problem Statement
Flamingo inserts new cross-attention layers into a frozen LM and initializes them to be no-ops via a tanh gate that starts at zero. Implement the gated residual so the model behaves identically to the base LM at initialization.
Background
A gated cross-attention block adds its attention output back through a learnable scalar gate alpha:
At alpha = 0, tanh(0) = 0, so y = x exactly — the injected layer is invisible and the frozen LM is preserved. As training moves alpha away from 0 the visual pathway gradually opens. Given x, the precomputed attn_out, and alpha, return y.
Your Task
Implement:
def gated_cross_attention(x, attn_out, alpha):
Return y as a list rounded to 4 decimals.
Input Format
- x, attn_out: lists of the same length D.
- alpha (float): the gate pre-activation.
Output Format
- A list of D floats rounded to 4 decimals.
Sample
print(gated_cross_attention([1.0, 2.0], [10.0, 10.0], 0.0))
Output:
[1.0, 2.0]
Example
print(gated_cross_attention([1.0, 2.0], [10.0, 10.0], 0.0))
[1.0, 2.0]
- Calculate the gate activation by applying the hyperbolic tangent to the input : . This step determines the scaling factor for the attention output, ensuring the layer acts as a no-op at initialization.
- Scale the attention output vector by the gate value: . This zeroes out the contribution of the cross-attention mechanism.
- Add the scaled attention output to the input vector to compute the residual connection: . This preserves the original input values since the gate is closed.
- Round each element of the resulting vector to 4 decimal places: remains . This ensures the output meets the required precision format.
- The final output is [1.0, 2.0]
Constraints
1 <= D <= 4096.- The gate is
tanh(alpha); atalpha == 0the block is an exact identity. - Round every entry to 4 decimals; avoid
-0.0.