PIXELBANKv9.1.0
Menu

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:

y=x+tanh⁡(α)⋅attn_outy = x + \tanh(\alpha)\cdot \text{attn\_out}

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:

Input:
print(gated_cross_attention([1.0, 2.0], [10.0, 10.0], 0.0))
Output:
[1.0, 2.0]
Reasoning:
  • Calculate the gate activation by applying the hyperbolic tangent to the input α\alpha: tanh⁡(0.0)=0.0\tanh(0.0) = 0.0. 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: [10.0,10.0]⋅0.0=[0.0,0.0][10.0, 10.0] \cdot 0.0 = [0.0, 0.0]. This zeroes out the contribution of the cross-attention mechanism.
  • Add the scaled attention output to the input vector xx to compute the residual connection: [1.0,2.0]+[0.0,0.0]=[1.0,2.0][1.0, 2.0] + [0.0, 0.0] = [1.0, 2.0]. This preserves the original input values since the gate is closed.
  • Round each element of the resulting vector to 4 decimal places: [1.0,2.0][1.0, 2.0] remains [1.0,2.0][1.0, 2.0]. 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); at alpha == 0 the block is an exact identity.
  • Round every entry to 4 decimals; avoid -0.0.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Gated Cross-Attention (Flamingo tanh Gate) - Medium | PixelBank